2017-07-21 20 views
0

有很多文章写在我指定的主题上。但是,所有这些似乎都不起作用。至少在我的情况下。即使在用户手动关闭应用程序后,我也只是想一直运行我的服务。我不想要前台服务,因为它在状态栏中显示一些通知图标。我想要定期服务来完成我的要求。或者请建议是否有其他可用的替代方案来实现这一点。我尝试使用return START_STICKY作为onStartCommand回拨的返回值。我也尝试过使用广播接收器,但无论如何也无济于事。请帮助我。即使在应用程序关闭/杀死后,如何让服务在后台运行?

+0

有没有选择在后台甚至杀害力运行后您服务! –

回答

1

您可以在服务类的onTaskRemoved()方法中创建5分钟的警报。它将在5分钟后自动调用并重新启动服务。

在服务类

public void onTaskRemoved(Intent rootIntent) { 
    Intent restartService = new Intent(getApplicationContext(), YourService.class); 
    restartService.setPackage(Yourpackagename); 
    PendingIntent restartServiceIntent = PendingIntent.getService(getApplicationContext(), 1, restartService, PendingIntent.FLAG_ONE_SHOT); 
    AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE); 
    alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealTime()+1000, restartServiceIntent); 
} 
+0

你可以使用报警管理器的setExactAlarm()方法。一旦它被执行,这将清除警报。 –

0

您可以通过实现在Android中AlarmManger概念实现这一功能。一旦你想到实现这个后台服务,请看下面的URL。

提示:在实施之前,您应该确定这一点。因为它会消耗很多电量。

好运

http://stacktips.com/tutorials/android/repeat-alarm-example-in-android

https://developer.android.com/reference/android/app/AlarmManager.html

+0

感谢您的回复。如果应用程序已卸载,我希望服务停止。但是,android中的闹钟不会停止,直到手机启动。是不是? – user3782869

相关问题