解决安卓8.x 前台服务不显示的问题

本文转载自:https://blog.csdn.net/nowtodays/article/details/82430171

安卓8.0开始对推送系列做了更严格的规定 
在发送推送时需要对api版本进行判断 
这里先简单贴一下新版的适配方式,详细的教程可以参考大神文档: 
Android通知栏微技巧,8.0系统中通知栏的适配 -郭霖

用如下方式启动一个前台服务:

  //Service代码
  private final String CHANNEL_ID = "TEST_SERVICE_ID";
  private final String CHANNEL_NAME = "渠道一";

  private final String contentSub = "小标题";
  private final String contentTitle = "标题";
  private final String contentText = "测试前台服务";


  Notification notification;
  Notification.Builder builder;

  @Override
  public void onCreate() {
      super.onCreate();
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
          NotificationChannel chan = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
          chan.enableLights(true);
          chan.setLightColor(Color.RED);
          chan.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
          NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
          assert manager != null;
          manager.createNotificationChannel(chan);

          builder = new Notification.Builder(this, CHANNEL_ID);
          notification = builder
                  .setSmallIcon(R.mipmap.ic_launcher)
                  .setContentText(contentText)
                  .setSubText(contentSub)
                  .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                  .setContentTitle(contentTitle)
                  .build();
      } else {
          Intent i = new Intent();
          PendingIntent p = PendingIntent.getActivity(this, 1, i, 0);
          notification = new Notification.Builder(getApplicationContext())
                  .setContentInfo(contentSub)
                  .setSubText(contentSub)
                  .setContentTitle(contentTitle)
                  .setContentText(contentText)
                  .setWhen(System.currentTimeMillis())
                  .setSmallIcon(R.mipmap.ic_launcher)
                  .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                  .setContentIntent(p)
                  .build();
      }
  }

  @Nullable
  @Override
  public IBinder onBind(Intent intent) {
      return null;
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
      startForeground(1, notification);
      return START_STICKY;
  }

开启服务

//启动前台Service
 Intent i = new Intent(this, TestService.class);
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
     startForegroundService(i);
 } else {
     startService(i);
 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值