首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android -服务保持活力

Android -服务保持活力
EN

Stack Overflow用户
提问于 2012-07-13 19:01:01
回答 3查看 3K关注 0票数 0

系统有问题。我有运行服务,它不断地检查位置,并计算距离和时间,因为用户启动它。但在20-25分钟后,与其他应用程序的许多交互服务将被终止。

我怎样才能防止它呢?

我在考虑增加第二个服务,这将使我的生活。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-07-13 19:34:32

1、最小化服务的内存使用量

2、使您的服务前台,例如在服务的onCreate方法中

代码语言:javascript
复制
@Override
public void onCreate()
{
     super.onCreate();
    
     Notification notification = new Notification(R.drawable.icon_app_small, getText(R.string.app_name),System.currentTimeMillis());
     Intent notificationIntent = new Intent(this, [yourService].class);
     PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
     notification.setLatestEventInfo(this, [name string], [notification msg string], pendingIntent);
     startForeground(Notification.FLAG_ONGOING_EVENT, notification);
}
票数 1
EN

Stack Overflow用户

发布于 2012-07-13 19:50:27

我不确定这是否适用于您,但我是这样实现的:

在我的例子中,我需要一个服务来保持每X分钟在后台运行一次,每当它关闭时(无论是由于内存使用还是主要活动转到后台并清理它),它将在下一个时间间隔到达时再次触发。我有以下组件和工作流程:

  1. 活动A. Main活动,我的应用程序的起点。
  2. 服务。我想在后台运行的服务,做它需要做的任何事情,

完成后关闭,每隔X分钟重新启动一次。

Activity onCreate方法将创建一个PendingIntent,,并将其自身和服务S传递给它,如下所示:

代码语言:javascript
复制
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Create an IntentSender that will launch our service, to be scheduled
    // with the alarm manager.
    periodicIntentSender = PendingIntent.getService(
              ActivityX.this, 0, new Intent(ActivityX.this, ServiceS.class), 0);

在我的活动中,我实现了一个AlarmManager,它将以"periodicIntentSender“(上面定义的)为参数,并基于用户首选项(connection_Interval)发送意图:

代码语言:javascript
复制
// Schedule the alarm to start
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(
  AlarmManager.ELAPSED_REALTIME_WAKEUP, 0, connection_Interval, periodicIntentSender);

AlarmManager将确保每X分钟发送一次意图。我的服务S一直在监听这个意图,并且每次发送这样的意图时都会被唤醒。一旦服务再次被触发,它的onHandleIntent方法就会被调用。

代码语言:javascript
复制
public class ServiceS extends IntentService implements LocationListener {
.
.
   /*
    * (non-Javadoc)
    * 
    * @see android.app.IntentService#onHandleIntent(android.content.Intent)
   */
    @Override
    protected void onHandleIntent(Intent intent) {
      <WHATEVER YOU NEED TO DO>
    }
}

希望这能有所帮助。

票数 2
EN

Stack Overflow用户

发布于 2012-07-13 19:05:18

,但在20-25分钟后,与其他应用程序的许多交互服务将被终止。

最有可能的原因是内存使用过多,然后自动内存管理器杀死了你的进程或长时间运行的操作,意思是@AljoshaBre。

我怎么才能防止它呢?

因此,我的第一个想法是检查您的Service是否正在以某种生命周期方法运行,例如在onResume()中,如果不是,您应该重新启动Service并再次执行它。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11469171

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档