Android初级工程师的service研究之路
最近感觉挺闲的,在公司工作一年多了,大多时间都在写网页,微信小程序,发现Android的东西写得越来越少了,好多东西都快忘了,现在来复习一下,就发现,Android四大组件的service我快不知道怎么写了。
今天特地去看了下以前收藏的郭神写得service文章,写得特别好,但是发现由于时间的原因,还是有一些坑在里面了,特别是方法的废弃。
主要来说明下方法废弃之后,用什么方法代替。
首先来看看以前的一种写法
public class MyService extends Service {
@Override
public void onCreate() {
super.onCreate();
Notification notification = new Notification(R.drawable.ic_launcher, "前台service通知测试", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ServiceActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, "前台service通知标题", "前台service通知内容", pendingIntent);
startForeground(0, notification);
}
}
这个写好之后运行时,我发现service没有起到作用,通知并没有出现。
后来我查阅资料后发现,最好写一个NotificationManager来作为Notification的管理器。改变后是这样的。
public class MyService extends Service {
@Override
public void onCreate() {
super.onCreate();
NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, "前台service通知测试--旧方法", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ServiceActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, "前台service通知标题--旧方法", "前台service通知内容--旧方法", pendingIntent);
manager.notify(0, notification);
}
}
这样更改之后,运行发现,果然能实现了前台service,通知出现了
实现了通知,但是又发现一个问题,就是这个写法里面的
Notification notification = new Notification(R.drawable.ic_launcher, "前台service通知测试--旧方法", System.currentTimeMillis());
Notification方法被打横线了,这就说明,Notification被废弃了,而且不止这一个方法,还有
notification.setLatestEventInfo(this, "前台service通知标题--旧方法", "前台service通知内容--旧方法", pendingIntent);
中的setLatestEventInfo方法也被废弃了。
那么就只有找其他方法来进行操作了。经过努力后我将代码改成了这样
public class MyService extends Service {
@Override
public void onCreate() {
super.onCreate();
//Notification的管理器
NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
//新建Notification.Builder对象
Notification.Builder builder = new Notification.Builder(this);
//设置点击通知的跳转页面
Intent notificationIntent = new Intent(this, ServiceActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
//设置通知的图标
builder.setSmallIcon(R.drawable.ic_launcher);
//添加弹出通知时候的信息
builder.setTicker("前台service通知测试--新方法");
//设置通知的标题
builder.setContentTitle("前台service通知标题--新方法");
//设置通知的内容
builder.setContentText("前台service通知内容--新方法");
//执行intent
builder.setContentIntent(pendingIntent);
//将Notification.Builder对象转为普通的Notification对象
Notification notification = builder.build();
//设置点击通知后通知会消失(Notification有各种参数,大家可自己尝试效果)
notification.flags |= Notification.FLAG_AUTO_CANCEL;
//运行Notification
manager.notify(0, notification);
}
}
如此写好之后,就会发现没有被废弃的方法,而且service也是可以执行的,看看效果图
本人第一次写博客,有不足之处,欢迎大家批评指出,谢谢······