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()。并且在循环完成后服务被销毁。我在网上搜索,但找不到任何解决方案。
发布于 2020-07-06 23:25:16
如果“服务在完成循环后被销毁”,您可以使用break语句提前停止循环。尝试以下操作:
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: ");
}https://stackoverflow.com/questions/62757626
复制相似问题