我有一個GPS服務,其工作是獲取座標到服務器。這項服務假設全天候運行。但它在某種程度上被殺害了。 這隻適用於android v 2.3。在android v2.2上它運行良好。Android服務殺死Android 2.3(薑餅)
在這個服務中,我使用「LocationManager」,它的方法是「requestLocationUpdates」,它創建一個循環。這個循環負責獲取座標。所以我的目標是保持循環運行。
那麼該怎麼做,通過服務24/7運行。
我有一個GPS服務,其工作是獲取座標到服務器。這項服務假設全天候運行。但它在某種程度上被殺害了。 這隻適用於android v 2.3。在android v2.2上它運行良好。Android服務殺死Android 2.3(薑餅)
在這個服務中,我使用「LocationManager」,它的方法是「requestLocationUpdates」,它創建一個循環。這個循環負責獲取座標。所以我的目標是保持循環運行。
那麼該怎麼做,通過服務24/7運行。
請使用重複報警管理器,它啓動您的服務給定時間段內
private void setAlarm() {
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), LocationUpdateService.class);
intent.putExtra("locationSendingAlarm", true);
PendingIntent pendingIntent = PendingIntent.getService(this, AppConstants.PENDING_INTENET_LOCATION_SENDING_ALARM_ID, intent,0);
try {
alarmManager.cancel(pendingIntent);
} catch (Exception e) {
}
int timeForAlarm=5*1000*60; // 5 minutes
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+timeForAlarm, timeForAlarm,pendingIntent);
}
只要您在獲取服務信息的任何地方創建通知並更新通知。如果通知被添加,那麼os知道一些重要的進程正在運行,否則當os需要內存時它會自動終止進程。 – Hulk 2013-12-05 06:58:07
This server suppose to be run 24/7
您後不能做到這一點。正如你所發現的,這是任何真正意義上的not possible。它也是not a good design choice。
如果您絕對需要它一直在運行,您需要 通過PowerManager
獲取PARTIAL_WAKE_LOCK
。這將一直保持CPU ,並且您的程序正在運行。準備好一個令人震驚的電池壽命下降 。
改爲使用AlarmManager。您可以通過在相關時間點啓動服務的AlarmManager來安排PendingIntent以完成工作。完成後,再次終止服務。
下面是顯示AlarmManager是如何使用的樣本代碼,將推出意圖在5分鐘內開始YourService從現在開始:
// get a calendar with the current time
Calendar cal = Calendar.getInstance();
// add 5 minutes to the calendar object
cal.add(Calendar.MINUTE, 5);
Intent intent = new Intent(ctx, YourService.class);
PendingIntent pi = PendingIntent.getService(this, 123, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pi);
感謝您的回覆,我正在檢查您的選項。 – user1594568 2012-08-13 11:17:08
你可以張貼代碼..所以我們可以幫助您更好地.. – 2012-08-13 06:57:31