首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >stopSelf()没有调用onDestroy()

stopSelf()没有调用onDestroy()
EN

Stack Overflow用户
提问于 2020-07-06 21:56:17
回答 1查看 54关注 0票数 0
代码语言:javascript
复制
public int onStartCommand(Intent intent, int flags, int startId) {

        for (int i=0;i<150;i++)
       {
           Log.d(TAG, "onStartCommand: "+i);
           if (i==10)
           {
               stopSelf();
               Log.d(TAG, "onStartCommand: stop");
           }

       }

        return super.onStartCommand(intent,flags,startId);
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy: ");
    }

我正在学习Android中的Service。这是我的代码。当我在for循环外部编写stopSelf();时,它工作得很好。但是,当在循环中编写时,即使满足条件,也不会调用stopSelf()。并且在循环完成后服务被销毁。我在网上搜索,但找不到任何解决方案。

EN

回答 1

Stack Overflow用户

发布于 2020-07-06 23:25:16

如果“服务在完成循环后被销毁”,您可以使用break语句提前停止循环。尝试以下操作:

代码语言:javascript
复制
public int onStartCommand(Intent intent, int flags, int startId) {

    for (int i=0;i<150;i++)
   {
       Log.d(TAG, "onStartCommand: "+i);
       if (i==10)
       {
           stopSelf();
           Log.d(TAG, "onStartCommand: stop");
           break; // This will stop the loop.
       }

   }

    return super.onStartCommand(intent,flags,startId);
}

@Override
public void onDestroy() {
    Log.d(TAG, "onDestroy: ");
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62757626

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档