Android 保持服务运行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12016623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Keep Service running
提问by Marc Ortiz
Can anyone tell me the way to keep a Service always running or restarting itself when the user close it? I've watched that facebook services restart when i clear memory. I don't want to make ForegroundServices.
谁能告诉我在用户关闭服务时保持服务始终运行或重新启动的方法吗?当我清除记忆时,我已经看到 facebook 服务重新启动。我不想制作 ForegroundServices。
回答by auselen
You should create a sticky service. Read more about it here.
您应该创建一个粘性服务。在此处阅读更多相关信息。
You can do this by returning START_STICKY in onStartCommand.
您可以通过在 onStartCommand 中返回 START_STICKY 来完成此操作。
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
Read also about application:persistentwhich is "Whether or not the application should remain running at all times". This is more troublesome - System will try not to kill your app which will effect others in the system, you should be careful using it.
另请阅读有关application:persistent 的内容,即“应用程序是否应始终保持运行状态”。这比较麻烦——系统会尽量不杀死你的应用程序,这会影响系统中的其他应用程序,你应该小心使用它。
回答by Hossam Alaa
I copied this from a service I used in an app I did before.
我从我之前在一个应用程序中使用的服务中复制了这个。
ITS IMPORTANT TO NOT UPDATE ANY UI. because you have no user interface in services. this applies to Toasts as well.
重要的是不要更新任何 UI。因为您在服务中没有用户界面。这也适用于 Toast。
good luck
祝你好运
public class nasserservice extends Service {
private static long UPDATE_INTERVAL = 1*5*1000; //default
private static Timer timer = new Timer();
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate(){
super.onCreate();
_startService();
}
private void _startService()
{
timer.scheduleAtFixedRate(
new TimerTask() {
public void run() {
doServiceWork();
}
}, 1000,UPDATE_INTERVAL);
Log.i(getClass().getSimpleName(), "FileScannerService Timer started....");
}
private void doServiceWork()
{
//do something wotever you want
//like reading file or getting data from network
try {
}
catch (Exception e) {
}
}
private void _shutdownService()
{
if (timer != null) timer.cancel();
Log.i(getClass().getSimpleName(), "Timer stopped...");
}
@Override
public void onDestroy()
{
super.onDestroy();
_shutdownService();
// if (MAIN_ACTIVITY != null) Log.d(getClass().getSimpleName(), "FileScannerService stopped");
}
}