Android 前台服务
添加权限
1
| <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
|
创建前台服务
1 2 3 4 5 6 7 8 9
| if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel("Example","Example", NotificationManager.IMPORTANCE_HIGH); ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).createNotificationChannel(channel); } NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "Example"); builder.setSmallIcon(R.mipmap.ic_launcher); builder.setContentTitle("Example"); builder.setContentText("Running"); startForeground(1, builder.build());
|
前台服务需要创建一个channel用来显示在通知栏
关闭服务