android 前台服务自定义布局不显示_Android使用前台服务

Android使用前台服务和普通服务在代码上的区别也就是一个Notification,代码如下:

public class MyService extends Service {

@Nullable

@Override

public IBinder onBind(Intent intent) {

return null;

}

@Override

public void onCreate() {

super.onCreate();

Logger.t("MyService").i("onCreate");

NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

builder.setSmallIcon(R.mipmap.ic_launcher);

builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));

builder.setContentTitle("title");

builder.setContentText("text");

builder.setWhen(System.currentTimeMillis());

Intent notificationIntent = new Intent(this, MainActivity.class);

PendingIntent pt = PendingIntent.getActivity(this, 0, notificationIntent, 0);

builder.setContentIntent(pt);

Notification notification = builder.build();

startForeground(1, notification);

}

@Override

public int onStartCommand(Intent intent, int flags, int startId) {

Logger.t("MyService").i("onStartCommand");

return super.onStartCommand(intent, flags, startId);

}

@Override

public void onDestroy() {

super.onDestroy();

Logger.t("MyService").i("onDestroy");

}

}

要从前台删除服务,需要调用stopForeground()方法,这个方法需要一个布尔型参数,指示是否删除状态栏通知。这个方法不终止服务。但是,如果你终止了正在运行的前台服务,那么通知也会被删除。

下面谈谈这期间遇到的蛋疼的事,直接上图对比:

before.gif

after.gif

一开始我写完代码运行,一直是图before的效果,检查代码一遍又一遍,也没发现问题出在哪里,就在我几近崩溃的时候,想着是不是因为我没设置小图标,就试着设置了下图标,结果就ok了,之后我又复习了一下Notification的知识,原来不设置小图标Notification根本显示不出来,哎~

builder.setSmallIcon(R.mipmap.ic_launcher);

顺便附上学习Notification时参考过的好文一篇——郭神(郭霖)之《Android通知栏的微技巧》

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值