【发布时间】:2014-08-12 15:04:48
【问题描述】:
我的应用使用 gcm 模块来监听通知,并为每个新的通知显示 android 通知。此外,当前窗口会更新为未读消息的新计数。
这个窗口是使用Ti.UI.createWindow({exitOnClose:true})创建的
问题是,当用户按下后退按钮时,应用程序会停止。这意味着,我不再收到任何通知,因此无法在通知栏中显示它们。
有没有办法让钛在按下后退按钮时隐藏应用程序,但不停止它,让我的代码仍然在后台运行?
我知道启动服务的可能性,但这样做的缺点是我无法更新我的窗口,当它当前对用户可见时,因为似乎没有办法在服务和应用程序之间进行通信。或者有什么办法?
app.js
//this is the most important line in this code.
//if I do exitOnClose:true, I stop receiving notifications every 5 seconds when pressing the back button (not good!, I want to keep getting notifications)
//if I do exitOnClose:false, I go back to a blank, "powered by titanium" window, when pressing the back button (not good!, I want the app to go to the background)
var win = Ti.UI.createWindow({exitOnClose:true});
//not part of the question
var label = Ti.UI.createLabel({text:"0"});
win.add(label);
win.open();
var notifications = [];
//listen for notifications (not part of the question)
listenForNotifications(function(notification){
//handle the notification
notifications.push(notification);
//update window
label.text = "Notification Count: "+notifications.length;
//display notification in title bar
displayNotificationInTitleBar(notification);
})
//this function is just dummy code to simulate listening for notifications in background using the gcm module
//it simulates a new notification every 5 seconds with an always increasing id
//it actually does not matter what module I use for notifications, Just take it as given that there runs code in the background,
//that I don't want to stop, after the user taps the backbutton
function listenForNotifications(cb){
var i = 0;
setInterval(function(){
cb({id:i++});
},5000);
}
//This function is actually not part of the question, it's just a sample
function displayNotificationInTitleBar(notification){
var intent = Ti.Android.createIntent({
action: Ti.Android.ACTION_MAIN,
packageName:"com.company.backgroundnotificationstest",
className:"com.company.backgroundnotificationstest.BackgroundnotificationstestActivity",
flags:Ti.Android.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Ti.Android.FLAG_ACTIVITY_SINGLE_TOP
});
intent.addCategory(Ti.Android.CATEGORY_LAUNCHER);
intent.putExtra("notificationid",notification.id);
Titanium.Android.NotificationManager.notify(notification.id, Titanium.Android.createNotification({
contentTitle: "New Notification",
contentText : "ID: "+notification.id,
contentIntent: Ti.Android.createPendingIntent({
intent:intent,
type : Ti.Android.PENDING_INTENT_FOR_ACTIVITY
}),
flags : Titanium.Android.ACTION_DEFAULT | Titanium.Android.FLAG_AUTO_CANCEL | Titanium.Android.FLAG_SHOW_LIGHTS
}));
}
示例应用程序位于:https://github.com/VanCoding/TitaniumBackgroundNotificationsTest
随意编译并自己查看:)
【问题讨论】:
-
@Downvoter:为什么?关于如何改进问题的任何建议?如果没有,请再次投票,因为这是一个合法的问题,appcelerator 文档现在还没有回答。谢谢。
标签: javascript titanium