2012-07-13 67 views
0

有一个系统的问题。我已经在运行服务,它会不断检查位置并计算用户启动后的距离和时间。但是在20-25分钟之后,许多与其他应用程序的交互服务正在被杀死。Android - 服务保持活力

我该如何预防?

我正在考虑添加第二项服务,以保持我的生命。

+0

邮政编码snipet – Prachi 2012-07-13 11:05:19

+0

您应该尝试使用Alarm Manager进行服务,并以特定的定时器间隔使用Alarm Manager重新启动服务,它的工作原理类似于魅力 – Lucifer 2012-07-13 11:13:35

+0

我该怎么做?你能提供一个小例子吗?并把它作为我可以投票的答案发布。 – goodm 2012-07-13 11:15:42

回答

1

1,尽量减少你的服务的内存使用

2,让你的服务的前景,例如在服务的onCreate方法

@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

但经过20-25分钟和许多与其他应用程序的交互 服务正在被杀死。

最有可能它是由过多的内存使用情况造成的,然后自动内存管理器杀了你的流程或长时间运行的操作意味着@AljoshaBre

我该如何预防它?

所以我的第一个想法是检查你的Service在例如一些生命周期的方法运行在onResume(),如果没有,就应该重新启动Service并再次执行。

+0

或长时间运行的操作... – nullpotent 2012-07-13 11:07:01

+0

保持服务应用程序实例可能导致问题? – goodm 2012-07-13 11:09:25

+0

我认为不是,因为我的意思很可能是由于运行时间过长或内存管理器杀死了进程本身。 – Sajmon 2012-07-13 11:18:23

2

不知道这是否会为你工作,但我就是这样实施它:

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

  1. 活动A.主要活动,我的应用程序的起点。
  2. 服务S.我想在后台运行的服务,做任何需要做的事情,
    完成后关闭,并在每X分钟后重新开始。

活动onCreate方法将创建一个的PendingIntent,通过它本身和服务S,如下:

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)发送意图:

// Schedule the alarm to start 
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 
alarmManager.setRepeating(
    AlarmManager.ELAPSED_REALTIME_WAKEUP, 0, connection_Interval, periodicIntentSender); 

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

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> 
    } 
} 

希望这会有所帮助。

+0

将立即尝试。 – goodm 2012-07-13 12:02:58