前言
在学习前台服务的时候,按照郭霖大神的《第一行代码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方法来启动前台服务,这种写法经过实践是可以正常运行的。