Appcelerator Android服务后台停止

4

我在使用Appcelerator时遇到了问题,与Android后台服务有关。 服务已启动,当我按下Home键时,服务仍在运行,当我点击返回按钮时也是如此。 但是当我从最近的应用列表中删除我的应用程序(长按Home键),服务停止了。 以下是我的调用服务的代码:

var SECONDS = 6;
    // every 10 minutes
    var intent = Titanium.Android.createServiceIntent({
        url : 'myservice.js'
    });
    intent.putExtra('interval', SECONDS * 1000);
    intent.putExtra('message_to_echo', num);

    //in millimeter
    var service = Titanium.Android.createService(intent);

    service.addEventListener('resume', function(e) {
    //  num++;
    //  alert(num);
    });

    service.start();    

这是文件服务代码:

var service = Titanium.Android.currentService;
var intent = service.intent;
var message = intent.getStringExtra("message_to_echo");

var intent = Ti.Android.createIntent({
    flags : Ti.Android.FLAG_ACTIVITY_CLEAR_TOP | Ti.Android.FLAG_ACTIVITY_SINGLE_TOP,
    // Substitute the correct classname for your application
    className : 'com.mappa.angeli.MappaActivity',
});
intent.addCategory(Ti.Android.CATEGORY_LAUNCHER);

// Create a PendingIntent to tie together the Activity and Intent
var pending = Titanium.Android.createPendingIntent({
    intent: intent,
    flags: Titanium.Android.FLAG_UPDATE_CURRENT
});

// Create the notification
var notification = Titanium.Android.createNotification({
    // icon is passed as an Android resource ID -- see Ti.App.Android.R.
   // icon: Ti.App.Android.R.drawable.my_icon,
    contentTitle: 'Something Happened',
    contentText : 'Click to return to the application.',
   // tickerText: 'Our app made a notification!',
    defaults:Titanium.Android.NotificationManager.DEFAULT_SOUND,
    contentIntent: pending
});
// Send the notification.
Titanium.Android.NotificationManager.notify(0, notification);

如何持续运行服务,例如WhatsApp之类的应用程序? 请帮忙,这非常重要。 先行致谢!!!

目前在Appcelerator中还无法实现此功能,尽管原生应用程序可以做到。有类似的需求帖子,但仍然没有可靠的答案。 - Sharif Abu Darda
1个回答

0

首先,让我给你一些关于你的问题的背景,这样你就能理解其逻辑。

我对你的问题和结论的理解

即使在原生应用程序中,如果你正在使用后台服务,你所要求的是不可能实现的。

为什么会这样?

因为应用程序不再提供服务。该应用程序被强制从后台中移除,因此操作系统停止了所有在后台运行的服务以清除内存。

大多数默认播放器播放音乐的方式是使用前台服务,并显示一个通知,说明应用程序正在运行并在后台处理某些事情(在这种情况下是播放歌曲)。

你可以考虑的选项

我建议你向你的应用程序添加“推送通知服务”,而不是选择“后台服务”。即使你的应用程序不在后台,你也会收到通知(就像 WhatsApp 一样)。

您可以通过以下链接实现 Android 的 GCM 推送服务

http://www.tidev.io/2013/12/20/using-gcm-for-android-push-notifications-with-acs/

希望这能帮到您。

祝您好运,加油!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接