永远在后台运行服务

时间:2014-06-26 10:06:05

标签: java android multithreading

我正在开发一个Android应用程序,我必须将当前时间与文件中的时间(已保存)进行比较,尽管一切正常。我有使用服务,在服务中我使用THREAD无限运行服务,除此之外,我还使用PARTIAL_WAKE_LOCK继续服务,即使设备处于睡眠状态,但问题是不是获取PARTIAL_WAKE_LOCK,而是我的服务运行1 / 2个小时然后再次入睡。我不想获得FULL_WAKE_LOCK。是否有人可以指导我为了进行这种比较而必须做的事情,即一旦用户设定时间,我的服务就会完美运行。

提前谢谢。

1 个答案:

答案 0 :(得分:2)

你这样做是错误的。要创建永久性服务,您必须 将其声明为前景。别无他法:

myService.startForeground(MY_NOTIFICATION_ID, my_notification);

如果您对此类服务的兴趣是定期执行快速结束 行动,如果期间很长,你可能想要使用 alarm API并改善您应用的电池消耗。

编辑:

要设置前台服务,您必须向系统提供通知 只要服务位于前台

,就会在的通知栏中显示该对象

为什么?因为前台服务无法被杀死,Android需要知道 用户知道这一事实。

设为前景:

static final int NOTIF_ID = 100;

// Create the FG service intent 
Intent intent = new Intent(getApplicationContext(), MyActivity.class); // set notification activity
showTaskIntent.setAction(Intent.ACTION_MAIN);
showTaskIntent.addCategory(Intent.CATEGORY_LAUNCHER);
showTaskIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

PendingIntent pIntent = PendingIntent.getActivity(
                getApplicationContext(),
                0,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

Notification notif = new Notification.Builder(getApplicationContext())
                .setContentTitle(getString(R.string.app_name))
                .setContentText(contentText)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentIntent(pIntent)
                .build();

startForeground(NOTIF_ID, notif);

然后回到标准'服务方式:

stopForeground(true).

设置为前台和恢复到后台都可以由服务本身(例如其onCreate()方法)或外部代码(例如,启动服务的活动)调用。这里没问题。