关闭应用程序时自动启动服务

时间:2011-03-05 09:25:26

标签: android

我创建了一个应用程序,它将启动一项服务来检查特定的远程文件以进行更新。

服务部分已完成,但现在用户需要手动启动服务

有一种方法可以让应用程序不在视图中时自动启动服务(用户单击主页按钮/单击或打开另一个应用程序)

++++++++++ ANSWER ++++++++++

无论如何都想出了如何做到这一点

    @Override
protected void onPause() 
{
    startService(new Intent(this, fileService.class));
    super.onPause();
}

@Override
protected void onResume() 
{
    stopService(new Intent(this, fileService.class));
    super.onResume();
}

我使用它在应用程序暂停时启动服务,在恢复时停止

2 个答案:

答案 0 :(得分:2)

您不能在应用程序级别执行此操作,而是在活动级别执行此操作。 Activities have a lifecycle,当状态发生变化时会收到通知。

您需要在Activity中实现onPause()或onStop()。

答案 1 :(得分:0)

我认为答案应该清楚而简单,以满足其他需求。



@Override
protected void onPause() {
  startService(new Intent(this, YourService.class));
  super.onPause();
}

@Override
protected void onResume() {
  stopService(new Intent(this, YourService.class));
  super.onResume();
}




相关问题