1.使用前台服务
要加上权限
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
//android 8.0以后新增 String CHANNEL_ONE_ID="com.example.servicetest"; String CHANNEL_ONE_NAME = "Channel One"; NotificationChannel notificationChannel = null; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ notificationChannel = new NotificationChannel(CHANNEL_ONE_ID,CHANNEL_ONE_NAME, notificationmanager.IMPORTANCE_HIGH); notificationChannel.enableLights(true); notificationChannel.setLightColor(Color.RED); notificationChannel.setShowBadge(true); notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); notificationmanager manager = (notificationmanager)getSystemService(NOTIFICATION_SERVICE); manager.createNotificationChannel(notificationChannel); //创建前台服务 Intent intent = new Intent(this,MainActivity.class); PendingIntent pi = PendingIntent.getActivity(this,0,intent,0); Notification notification = new Notification.Builder(this) .setChannelId(CHANNEL_ONE_ID)//新增 .setContentTitle("This is content title") .setContentText("This is content title") .setWhen(System.currentTimeMillis()) .setSmallIcon(R.mipmap.ic_launcher) .setContentIntent(pi) .build(); notification.flags |= Notification.FLAG_NO_CLEAR;//新增 startForeground(1,notification); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。