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方法来启动前台服务,这种写法经过实践是可以正常运行的。
相关文章推荐
- 二十六个月Android学习工作总结【转】
- Android ImageView的scaleType属性与adjustViewBounds属性
- 史上最全的Android 图片滤镜 colorMatrix自定义任意图片滤镜
- Android NDK 编译FFMPEG 问题
- Android快速开发不可或缺的11个工具类(下载)
- android 美团多渠道打包详解
- android 向serverGet和Post请求的两种方式,android向server发送文件,自己组装协议和借助第三方开源
- 下载android4.4.2源码全过程(附已下载的源码)
- Android studio 导入项目报 Error:Cause: peer not authenticated 异常
- Android重写EditText回车等事件
- Android Studio so文件如何添加,如何解决极光推送无法推送的奇怪问题
- 预置第三方apk
- Android基于ImageSwitcher实现图片切换功能
- 快速Android开发系列通信篇之EventBus(2)之BroadcastReceiver和EventBus区别
- android camera2人脸识别流程分析
- Android 判断是否有外网连接
- android怎样写一个循环文字滚动的TextView
- Android:滑动
- Android ViewPagerIndicator
- AndroidStudioTutorial_160217S002_启动Activity