您的位置:首页 > 移动开发 > Android开发

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

2016-02-17 14:52 507 查看

前言

在学习前台服务的时候,按照郭霖大神的《第一行代码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方法来启动前台服务,这种写法经过实践是可以正常运行的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: