当前位置: 移动技术网 > 移动技术>移动开发>Android > Android实现Service在前台运行服务

Android实现Service在前台运行服务

2019年07月24日  | 移动技术网移动技术  | 我要评论
前言 在做手机音乐播放器的时候,让我非常苦恼的一件事就是手机有清理内存的软件,比如百度,360等等,一点击清理音乐就停止播放了,去后台查看发现service已经被停止并重

前言

在做手机音乐播放器的时候,让我非常苦恼的一件事就是手机有清理内存的软件,比如百度,360等等,一点击清理音乐就停止播放了,去后台查看发现service已经被停止并重新启动了,这显然不是我想要的,我希望音乐能够在后台播放,并且自己能控制什么时候退出,不想让系统给我清理了,就像酷狗一直在通知栏显示那样,于是我就知道了在前台运行的服务。

实现

我们先看一下结果图:

这是运行在通知栏的界面,这样就是让服务在前台运行,再清理的时候就不会导致服务被关闭了。

好了,我们直接上代码,因为要开启服务,所以我们必须先要有一个service的子类,然后在oncreate里面实现它。

myservice.java

public class myservice extends service {

 public static final string tag = "myservice";

 @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);

 }
 @override
 public int onstartcommand(intent intent, int flags, int startid) {
  return super.onstartcommand(intent, flags, startid);
 }

 @override
 public void ondestroy() {
  super.ondestroy();
 }

 @override
 public ibinder onbind(intent intent) {
  return null;
 }

}

可以看到,在oncreate方法里面我们得到notification的一个对象,然后调用startforeground(1, notification);方法来实现在前台运行。如果想要退出只需要退出服务即可。

小结

在前台运行服务是十分有用的,特别是在做播放器开发的时候,如果只是简单的清理一下音乐就退出播放了,这是很不能容忍的。

像酷狗一样,在通知栏有自己notification的自定义界面,下一篇文章我说明如何自定义notification的界面。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网