Android前台服务 音乐播放器 前台服务

来源:互联网 发布:道家经典软件下载 编辑:程序博客网 时间:2024/04/29 21:23

前台服务,即foreground service. 前台服务的优先级是比较高的,android系统极少会主动杀死前台服务。类似音乐播放器后台播放功能,就是需要启动一个前台服务。下面的代码显示了如何启动一个前台服务。


String songName;// assign the song name to songNamePendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0,                new Intent(getApplicationContext(), MainActivity.class),                PendingIntent.FLAG_UPDATE_CURRENT);Notification notification = new Notification();notification.tickerText = text;notification.icon = R.drawable.play0;notification.flags |= Notification.FLAG_ONGOING_EVENT;notification.setLatestEventInfo(getApplicationContext(), "MusicPlayerSample",                "Playing: " + songName, pi);startForeground(NOTIFICATION_ID, notification);

当前台服务在运行时,前台服务可以在通知栏里面被看到,当被选择时,系统会唤醒上面已经定义了的pi提供的activity,即MainActivity,它是一个 pendingintent。


当不使用时,需要关闭服务,调用

stopForeground(true);

结束服务。