资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

Android实现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;
 }

}


网站栏目:Android实现Service在前台运行服务-创新互联
链接地址:http://cdkjz.cn/article/dphdii.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220