我正在开发一个 Android 应用程序,在该应用程序中我必须将当前时间与文件中的时间(已保存)进行比较,尽管一切正常。我使用过服务,在服务中我使用 THREAD 无限运行服务,除此之外,我还使用 PARTIAL_WAKE_LOCK 继续服务,即使设备处于 sleep 状态,但问题是我的服务不是获取 PARTIAL_WAKE_LOCK,而是运行 1/2小时,然后再次休眠。我不想获得 FULL_WAKE_LOCK。有没有人可以指导我必须做什么才能运行此比较,即一旦用户设置时间,我的服务将完美运行。
提前谢谢你。
最佳答案
你做错了。要创建永久服务,您必须 将其声明为前景。别无他法:
myService.startForeground(MY_NOTIFICATION_ID, my_notification);
如果您对此类服务的兴趣是定期执行快结 Action ,如果中间时间很长,你可能想使用 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() 方法)或外部代码(例如启动服务的 Activity )调用。这里没有问题。
关于java - 永远在后台运行服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24427675/