android创建前台服务,Android实现Service在前台运⾏服务前⾔
娄艺潇个人资料
在做⼿机⾳乐播放器的时候,让我⾮常苦恼的⼀件事就是⼿机有清理内存的软件,⽐如百度,360等等,⼀点击清理⾳乐就停⽌播放了,去后台查看发现Service已经被停⽌并重新启动了,这显然不是我想要的,我希望⾳乐能够在后台播放,并且⾃⼰能控制什么时候退出,不想让系统给我清理了,就像酷狗⼀直在通知栏显⽰那样,于是我就知道了在前台运⾏的服务。
实现
我们先看⼀下结果图:张靓颖离歌
这是运⾏在通知栏的界⾯,这样就是让服务在前台运⾏,再清理的时候就不会导致服务被关闭了。
好了,我们直接上代码,因为要开启服务,所以我们必须先要有⼀个Service的⼦类,然后在onCreate⾥⾯实现它。
MyService.javafootprints in the sand歌词
public class MyService extends Service {
public static final String TAG = "MyService";
@Override
public void onCreate() {
Notification notification = new Notification(R.drawable.ic_launcher,
"有通知到来", System.currentTimeMillis());爱的伤痕
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = Activity(this, 0,
notificationIntent, 0);
notification.setLatestEventInfo(this, "幻听", "许嵩",
pendingIntent);
startForeground(1, notification);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
StartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
you belong with me 歌词
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
闫学晶的现任丈夫是谁可以看到,在onCreate⽅法⾥⾯我们得到Notification的⼀个对象,然后调⽤startForeground(1, notification);⽅法来实现在前台运⾏。如果想要退出只需要退出服务即可。
⼩结
在前台运⾏服务是⼗分有⽤的,特别是在做播放器开发的时候,如果只是简单的清理⼀下⾳乐就退出播放了,这是很不能容忍的。
像酷狗⼀样,在通知栏有⾃⼰Notification的⾃定义界⾯,下⼀篇⽂章我说明如何⾃定义Notification的
界⾯。
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持脚本之家。