有人能告诉我如何让一个服务在用户关闭它后始终保持运行或重新启动吗?我注意到当我清除内存时,Facebook服务会重新启动。 我不想创建前台服务。
你应该创建一个sticky service。可以在onStartCommand中返回START_STICKY来实现该功能。更多信息请参阅这里。
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
还可以了解一下application:persistent,它表示“应用程序是否应始终保持运行状态”。这更加麻烦 - 系统将尝试不杀死您的应用程序,这会影响系统中的其他应用程序,因此您应该谨慎使用它。
application:persistent
不是一个好的做法。我认为这样做会真正增加电池消耗。 - busylee我从以前的一个应用程序中使用的服务中复制了这个。
在服务中,请勿更新任何UI,因为您在服务中没有用户界面。这也适用于Toast。
祝好运!
public class nasserservice extends Service {
private static long UPDATE_INTERVAL = 1*5*1000; //default
private static Timer timer = new Timer();
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate(){
super.onCreate();
_startService();
}
private void _startService()
{
timer.scheduleAtFixedRate(
new TimerTask() {
public void run() {
doServiceWork();
}
}, 1000,UPDATE_INTERVAL);
Log.i(getClass().getSimpleName(), "FileScannerService Timer started....");
}
private void doServiceWork()
{
//do something wotever you want
//like reading file or getting data from network
try {
}
catch (Exception e) {
}
}
private void _shutdownService()
{
if (timer != null) timer.cancel();
Log.i(getClass().getSimpleName(), "Timer stopped...");
}
@Override
public void onDestroy()
{
super.onDestroy();
_shutdownService();
// if (MAIN_ACTIVITY != null) Log.d(getClass().getSimpleName(), "FileScannerService stopped");
}
}