Android四大组件之服务Service(二)前台服务

前台服务和普通服务区别在于,他会一直运行在系统的状态栏,类似通知的效果。比如天气软件通知栏一样。

创建前台服务很简单,只需在新建的服务类的onCreate()方法中添加如下代码即可:

//重写onCreate(),服务创建时被运行
@Override
public void onCreate() {
    super.onCreate();
    Log.d("MyService","onCreate()执行了");  //打印日志,看是否创建了服务
    //当点击状态栏的服务时,跳转的页面:利用Intent创建PendingIntent的实例
    Intent intent=new Intent(this,MainActivity.class);  #pendingIntent的意图:目的页面是MainActivity.class
    PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,0); #获取pendingIntent实例
 
    //获取通知对象:借助NotificationCompat类的Builder创建通知对象,并设置属性
    Notification notification=new NotificationCompat.Builder(this)
                        .setContentTitle("我是标题")
                        .setContentText("这是内容")
                        .setWhen(System.currentTimeMillis())
                        .setSmallIcon(R.mipmap.ic_launcher)
                                        .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                        .setContentIntent(pendingIntent)
                        .build();
    //调用startForeground()方法,就会让此服务变为前台服务,并在状态栏显示
    startForeground(1,notification)
}

这里没用NotificationManager的notify(id, Notification)而是直接startForeground(id,notification)就会让此服务变为前台服务,并在状态栏显示

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值