Android学习(6)---前台服务notification.setLatestEventInfo 废弃之后的替代写法

前言

在学习前台服务的时候,按照郭霖大神的《第一行代码Android》中的例子,但是其中的notification.setLatestEventInfo方法已经废弃了,于是用最新的使用通知的方式来实现前台服务。

主要代码

代码位于service类的onCreate() 方法,之前的写法:
// 郭霖所使用的方法,setLatestEventInfo已经废弃,无法继续使用;
        Notification notification = new Notification(R.mipmap.ic_launcher, "Notification comes", System.currentTimeMillis());
        Intent notificationIntent = new Intent(this, AtyService.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        notification.setLatestEventInfo(this, "This is title", "This is content",
                pendingIntent);
        startForeground(1, notification);



改进之后的写法:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

        // 必需的通知内容
        builder.setContentTitle("content title")
                .setContentText("content describe")
                .setSmallIcon(R.mipmap.ic_launcher);

        Intent notifyIntent = new Intent(this, AtyService.class);
        PendingIntent notifyPendingIntent = PendingIntent.getActivity(this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(notifyPendingIntent);

        Notification notification = builder.build();
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        //manager.notify(1, notification);

        startForeground(1, notification);

使用Builder来初始化Notification,然后使用startForeground方法来启动前台服务,这种写法经过实践是可以正常运行的。
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值