Android enables the service to run in the foreground

preface

When I was working as a mobile music player, one thing that bothered me was that the mobile phone had software to clean up the memory, such as Baidu, 360, etc. when I clicked to clean up the music, it stopped playing. I went to the background to check and found that the service had been stopped and restarted. Obviously, this is not what I want. I hope the music can be played in the background and I can control when to quit, I don't want the system to clean up, just like the cool dog has been displayed in the notice bar, so I know the service running in the foreground.

realization

Let's look at the result chart first:

This is the interface running in the notification bar, so that the service can run in the foreground, and the service will not be shut down during cleaning.

Well, let's go directly to the code. To start the service, we must first have a subclass of the service, and then implement it in oncreate.

MyService.java

As you can see, in the onCreate method, we get an object of Notification and call startForeground (1, notification). Method to run in the foreground. If you want to exit, just exit the service.

Summary

It is very useful to run the service at the front desk, especially when developing the player. If you simply clean up the music and quit playing, it is intolerable.

Like cool dog, it has its own custom notification interface in the notification bar. In the next article, I will explain how to customize the notification interface.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>