也许这个问题很明显,但我想根据我的应用程序做些什么来确定。
我正在写一个GPS追踪器。我使用静态类中的位置服务来获取我的位置。一切正常。但是我注意到我的应用程序有时会在运行几个小时后被杀死。为了解决这个问题,我想把它转换成前台服务。
我没有重写我的代码并将所有逻辑放在服务中,而是考虑创建一个什么都不做的前台服务。当用户决定开始跟踪时,我将启动此服务。请记住,我在静态类中使用位置服务。
这是安全的还是操作系统会发现这项服务根本没有做任何事情而且会有更多的机会被杀?
这是我的服务:
public class SimpleService extends Service
{
private static final int ONGOING_NOTIFICATION = 1;
@Override
public void onCreate()
{
super.onCreate();
Notification notification = new Notification(R.drawable.icon, "Tracking started", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, "notification title", "notification message", pendingIntent);
startForeground(ONGOING_NOTIFICATION, notification);
}
@Override
public void onDestroy()
{
super.onDestroy();
stopForeground(true);
}
}
由于
答案 0 :(得分:1)
我为我创建的服务做了类似的事情,该服务定期运行以下载文件,如果它发生了变化,但发现它在几小时后被操作系统杀死了。自从使用startForeground
以来,问题就消失了。
我认为我的服务工作与空工作之间没有区别。