Service几乎都是在后台运行的,一直以来它都是默默地做着辛苦的工作。但是Service的系统优先级还是比较低的,当系统出现内存不足情况时,就有可能会回收掉正在后台运行的Service。
如果你希望Service可以一直保持运行状态,而不会由于系统内存不足的原因导致被回收,就可以考虑使用前台Service。前台Service和普通Service最大的区别就在于,它会一直有一个正在运行的图标在系统的状态栏显示,下拉状态栏后可以看到更加详细的信息,非常类似于通知的效果。当然有时候你也可能不仅仅是为了防止Service被回收才使用前台Service,有些项目由于特殊的需求会要求必须使用前台Service。
@Override
public void onCreate() {
super.onCreate();
Notification notification = new Notification(R.drawable.ic_launcher, "有通知到来", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, "这是通知的标题", "这是通知的内容",pendingIntent);
startForeground(1, notification);
Log.d(TAG, "onCreate() executed");
}
还有新的写法:
@Override
public void onCreate() {
super.onCreate();
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,new Intent(this, MainActivity.class), 0);
// 通过Notification.Builder来创建通知,注意API Level
// API16之后才支持
Notification notify = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("TickerText:" + "您有新短消息,请注意查收!")
.setContentTitle("Notification Title")
.setContentText("This is the notification message")
.setContentIntent(pendingIntent).setNumber(1).build(); // 需要注意build()是在API
// level16及之后增加的,API11可以使用getNotificatin()来替代
startForeground(1, notify);
Log.d(TAG, "onCreate() executed");
}
测试,两种方法都是可以的,只是第一种方法的函数已经不推荐使用了。当然,还有其它的方法来写,我们只要会第二种方法就可以了。