【问题标题】:Android startup Service onStart and another issueAndroid 启动 Service onStart 和另一个问题
【发布时间】:2011-08-21 08:05:06
【问题描述】:

我一直试图弄清楚这一点,但无法弄清楚为什么会发生这种情况。这似乎很简单,但我无法解决这个问题。

这是我想做的事

当我启动应用程序时,
1. 如果后台服务(长时间运行的单例服务)没有运行,请在启动活动之前启动它。
2.启动“首页”活动

更新于 8 月 20 日
发生了什么:

1. 我启动应用程序但服务没有运行
2. 我启动了意图(通过 context.startService)
- 调用 context.startService
3.活动结束
4. onStartCommand 运行

如何在 Activity 开始运行之前让 onStartCommand 运行?


对此的任何建议都会减轻很多挫败感。在问这个问题之前我已经搜索了论坛,但找不到任何与我的问题相匹配的内容
非常感谢!


更新
感谢您的快速回复。
我应该提到我已经从应用程序的扩展运行它(在 onCreate 方法中启动服务)。
在我当前的实现中(如下),当我逐步浏览应用程序时,会发生以下情况。我认为这会导致服务在活动之前运行,但活动运行然后服务运行。这是我困惑的重点。
1.应用onCreate被调用
2. startService 方法运行
3.启动活动运行
4.服务onCreate被调用
- 永远不会调用 onStart 服务(我将尝试使用 onStartCommand,因为我不针对旧平台 - 感谢 Alexander 的建议)

    public class MyApp extends Application {

@Override
public final void onCreate()
{

        if(!MyService.isRunning()) // this is a static method with thread lock
        {
            Intent i = new Intent(context, MyService.class);
            i.setAction(MyConstants.INTENT_START_SERVICE);
            context.startService(i);
        }
    }
}

【问题讨论】:

    标签: android android-service


    【解决方案1】:

    您可以创建一个扩展Application 类的新类。此类将在调用主要活动之前运行,并且仅在首次启动应用程序时运行。这是您可以在 主页 活动打开之前启动服务的地方。

    【讨论】:

    • +1。除非您也针对较旧的平台,否则最好使用 onStartCommand not deprecated onStart。
    • 现在正在调用 onStartCommand,但我无法在应用程序运行之前运行 onStartCommand。有没有办法让它工作?你能设置在activity之前运行的intent吗?
    【解决方案2】:

    感谢 Alexander O 的评论为我指明了运行 onStart 命令的正确方向。我仍然无法让 onStartCommand 在活动之前运行。有什么建议么?

    我的问题是我的服务中有一个 onStartCommand 和一个 onStart 函数。
    显然我没有理解onStartCommand的功能,以为它只是应该定义服务类型(STICKY,NOT_STICKY)。
    一旦我删除了 onStart 并将 onStart 代码移动到 onStartCommand 中,应用程序就开始工作了。
    对于那些想知道的人,这基本上就是我所拥有的。

    public class MyService extends Service
    {
     ...
        @Override
        public int onStartCommand(Intent intent, int flags, int startId)
        {
                // this was being executed but didn't really do anything
                return Service.START_STICKY;
        }
        ...
        @Override
        public void onStart(Intent intent, int startId)
        {
            // logic that was never executed
            // problem fixed when I removed onStart and moved the code to onStartCommand
        }
    }
    

    【讨论】:

    • 看起来好像没有办法强制 onStartCommand 在 Activity 之前按顺序运行。如果有人找到了这样做的方法,请告诉我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-10
    相关资源
    最近更新 更多