服务几乎都是在后台运行的,一直以来它都是默默地做着辛苦的工作。但是服务的系统优先级还是比较低的,当系统出现内存不足的情况时,就有可能会回收掉正在后台运行的服务。如果你希望服务可以一直保持运行状态,而不会由于系统内存不足的原因导致被回收,就可以考虑使用前台服务。有些项目由于特殊的需求会要求必须使用前台服务,比如说墨迹天气,他的服务在后台更新天气数据的同时,还会在系统状态栏一直显示当前的天气信息。
下面看下如何创建前台服务,创建MyService继承Service,重写onCreate()方法,如下代码所示:
@Override
public void onCreate() {
super.onCreate();
Notification notification = new Notification(R.drawable.ic_launcher,
"Notification comes", System.currentTimeMillis());
Intent notificationIntent = new Intent(this,MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, "This is title", "This is content", pendingIntent);
startForeground(1, notification);
Log.d("MyService", "onCreate executed");
}
构建出Notification对象,然后调用startForeground()方法。这个参数接受两个参数,第一个参数是通知的id,第二个参数则是构建出的Notification对象。调用startForeground()方法后就会让MyService变成一个前台服务,并在系统状态栏显示出来。
注:文章采摘自《第一行代码》