Service的使用(四)前台服务与AIDL

前台服务

前台服务优先级较高,在系统内存不足时,也不会考虑将其终止。 前台服务必须为状态栏提供通知,而且除非服务停止或从前台删除,否则不能清除通知

应用:音乐播放器播放音乐的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机制达到进程间通信的目的。
项目地址

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值