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

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


String songName;
// assign the song name to songName
PendingIntent 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);

结束服务。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值