9.5.1使用前台服务
前台服务:和普通服务的最大区别在于,它会一直有一个正在运行的图标在系统的状态栏显示,下拉状态栏后可以看到更加详细的信息,非常类似于通知的效果。
如果你希望服务可以一直保持运行状态,而不会由于系统内存不足的原因导致被回收,可以考虑使用前台服务。
使用步骤:
1、在服务的onCreate()方法中构建出一个通知对象notification,然后对这个通知对象进行设置,调用其setLatestEventInfo()方法;
2、调用Context的startForeground()方法,就会让MyService变成一个前台服务,并在系统状态栏显示出来。
该方法接收两个参数:
第一个参数:是通知的id,类似于notify()方法的第一个参数;
第二个参数:是构建出的Notification对象。
代码示例:
Notificationnotification = 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);