【发布时间】:2014-12-26 11:38:53
【问题描述】:
我有一个 Activity 在 onCreate() 中调用 startService() 并带有一些参数。
该服务运行良好(我使用Timer),但是当我退出活动(onPause() or onDestroy())时,会发生服务重新创建!它以空意图调用 onCreate 然后 onStartCommand() ! (正常)
那么我该怎么做才能重新获得旧意图呢?!
我认为有START_REDELIVER_INTENT 但是如何使用它!这是正确的方法吗?
PS:为什么尽管extends Service 却被杀死了?是否取决于活动的生命周期 => 那么谁又给他打电话了?
public class MyService extends Service {
private static Timer timer = new Timer();
@Override
public void onCreate() {
Log.d(TAG, "onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent != null){
Bundle bundle = intent.getExtras();
if (bundle != null)
{
timer.scheduleAtFixedRate(new Action(),15000 , 15000);
}
}
Action() {
timer = new Timer();
timer.scheduleAtFixedRate(new Action(),15000 , 15000);
}
}
【问题讨论】:
-
您是否取消了关闭Activity的计时器?计时器在不同的线程上运行可能会导致此问题。尝试通过
your_timer_object.Cancel();取消 Activity 关闭时的计时器@ -
你在 onStartCommand() 返回方法时写了什么代码。您是否返回“返回 START_STICKY”。如果是,则服务将自行重启。你必须调用 stopSelf() 或 stopService(Intent service)
-
@VipinSharma 即使我退出应用程序,计时器仍然可以工作!但也许在短时间内它会取消或其他!
-
我注意到对象计时器也重新创建了!我应该怎么做才能让一个实例一直运行?
-
@Rollno1 服务不应该自行重启!因为它有参数可以使用!