前台服务
前台服务优先级较高,在系统内存不足时,也不会考虑将其终止。 前台服务必须为状态栏提供通知,而且除非服务停止或从前台删除,否则不能清除通知。
应用:音乐播放器播放音乐的Service应该设置为在前台运行,状态栏中的通知表示正在播放的歌曲,并允许用户启动 Activity 来与音乐播放器进行交互。
前台服务本质还是一个服务,要继承Service进行实现。可以看做Service和Notification的混合。
public class ForegroundService extends Service {
private static final int NOTIFY_ID = 123;
@Override
public void onCreate() {
super.onCreate();
showNotification();
}
private void showNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(android.support.v7.appcompat.R.drawable.notification_template_icon_bg)
.setContentTitle("Title")
.setContentText("Content");
//创建通知被点击时触发的Intent
Intent intent = new Intent(this, ServiceActivity.class);
//创建TaskStackBuilder,管理任务栈
TaskStackBuilder taskBuilder = TaskStackBuilder.create(this);
taskBuilder.addParentStack(ServiceActivity.class);
taskBuilder.addNextIntent(intent);
//通知的事件触发具体要用PendingIntent,获取PendingIntent
PendingIntent pi = taskBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pi);
//获取NotificationManager,并启动通知
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = builder.build();
manager.notify(NOTIFY_ID,notification);
//启动为前台服务
startForeground(NOTIFY_ID,notification);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("TAG", "onStartCommand: ");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return super.onStartCommand(intent,flags,startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
注意:提供给 startForeground() 的整型 ID 不得为 0
删除前台服务,调用 stopForeground()
相关阅读:通知栏
AIDL
Android接口描述语言,通常用于进程间通信。编译器根据AIDL文件生成一个系列对应得Java类,通过预先定义的接口以及Binder机制达到进程间通信的目的。
项目地址