[英]Titanium (Android) check for running Services
我正在嘗試實現一個方便使用的系統來處理Android的狀態欄通知,我正在考慮以下內容:
唯一的問題是,如果我需要啟動服務,我無法檢測到。 我試過這些東西,但到目前為止它們都沒有奏效:
1.)如果服務已在本地存儲上啟動,請保存:
// Do this on application startup
var isRunning = Ti.App.Properties.getBool("service_running", false);
if(!isRunning)
{
var service = Titanium.Android.createService(...);
service.addEventListener('start', function()
{
Ti.App.Properties.setBool("service_running", true);
});
service.addEventListener('stop', function()
{
Ti.App.Properties.setBool("service_running", false);
});
service.start();
}
這顯然不起作用,因為如果服務沒有異常終止(如用戶強制停止應用程序),則不會調度android系統本機onStop
和onDestroy
事件,因此也不會觸發停止事件。
2.)嘗試通過Titanium.Android.getCurrentService()
訪問任何活動服務,但我得到一個錯誤,說Titanium.Android沒有名為getCurrentService()的方法。 這很奇怪,因為IDE代碼完成為我提供了這種方法。
3.)使用Intent清除以前運行的服務
var intent = Titanium.Android.createServiceIntent
(
{
url : 'notification/NotificationService.js'
}
);
intent.putExtra('interval', 1000 * 60);
//Stop if needed
Titanium.Android.stopService(intent);
//Then start it
Titanium.Android.startService(intent);
但似乎我需要擁有相同的Intent實例,啟動服務來阻止它,因為在應用程序啟動時執行此操作,然后退出並重新啟動它會導致運行多個服務。
在這一點上,我沒有想法,如何檢查運行服務。 如果您知道有任何方法可以做到這一點,請告訴我! 謝謝你的任何提示!
編輯
以下是源代碼材料,它讓我嘗試上述方法(也許只有我錯誤地使用它們):
以及我編寫的NotificationHandler“class”和NotificationService.js的完整源代碼及其用法: link
使用Bencoding AlarmManager
,它將提供安排警報通知所需的一切: https : //github.com/benbahrenburg/benCoding.AlarmManager
該模塊提供您所需的功能。 這很簡單 - 只需在安排Notification or Service
時將重復設置為daily
。
有關功能完整的代碼,請參閱https://gist.github.com/itsamiths/6248106
我正在檢查服務是否已啟動,然后顯示每日通知或啟動服務,然后顯示每日通知
var isRunning = Ti.App.Properties.getBool("service_running", false);//get service running bool status
if (isRunning) {
Ti.API.info('service is running');
} else {
Ti.API.info('service is not running');
alarmManager.addAlarmService({
service : 'com.mkamithkumar.whatstoday.DailyEventNotificatoinService',
hour : "08",
repeat : 'daily'
});
}
我來晚了一年,但也許這可以幫助其他人。
我們有同樣的想法:永遠運行服務並在每個周期進行檢查(我必須檢查20個不同的通信)。
我遇到了同樣的問題:如何檢測服務正在運行,不再運行以不重復檢查。
為了解決這個問題,我所做的是獲取每個周期的當前時間並將其保存到商店。
然后,在啟動新服務之前,我檢查上次執行是否到達時間:如果為true,則服務已停止,否則正在運行。
不是很優雅,但這是我發現的唯一方法,以避免用戶殺死應用程序(和服務)的問題。
這是我的服務“啟動器”的代碼。 在我的情況下,我測試了30秒遠:
exports.createAndroidServiceForNotifications = function(seconds) {
var moment = require('alloy/moment');
var diffSeconds = moment().diff(Ti.App.Properties.getString('serviceLastRun', new Date().getTime() - 60000), 'second');
if (diffSeconds > 30) {
var now = new Date().getTime();
var delta = new Date(now + (seconds * 1000));
var deltaMS = delta - now;
var intent = Ti.Android.createServiceIntent({
url : 'notificationsService.js'
});
intent.putExtra('interval', deltaMS);
Ti.Android.startService(intent);
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.