普通的 service 优先级比较低,当系统内存不足时,就有可能会回收掉正在后台运行的服务,如果希望服务一直运行而不被回收,则应该使用前台服务。
前台服务的特点是,会有一个正在运行的图标在状态栏显示,下拉状态栏会有更详细的信息,和通知的效果很相似。
创建前台服务,只需在 onCreate 中创建通知 Notification,然后调用 startForeground(notificationId, notification)
public int onStartCommand(Intent intent, int flags, int startId) { // 在API11之后构建Notification的方式 Notification.Builder builder = new Notification.Builder(this.getApplicationContext()); //获取一个Notification构造器 Intent nfIntent = new Intent(this, MainActivity.class); builder.setContentIntent(PendingIntent.getActivity(this, 0, nfIntent, 0)) .setContentTitle("下拉列表中的Title") // 设置下拉列表里的标题 .setContentText("要显示的内容") // 设置上下文内容 .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标 .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.mipmap.ic_launcher)) .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间 Notification notification = builder.build(); // 获取构建好的Notification notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音 startForeground(110, notification);// 开始前台服务 return START_NOT_STICKY; }