在Android中,退出APP界面后通过startService()方法启动的服务很快就会随之停止,在一些需求中需要在退出APP界面的情况下保证Service一直在运行,其中一个方法就是将Service设置成前台服务。设置前台服务首先需要在配置文件中添加权限:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
自定义通知消息的布局:
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.item_notification);
如果需要实现点击效果:
Intent intent = new Intent(MainActivity.this, NotificationActivity.class);
PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
notification.setContentIntent(pi)
然后在Service的onStartCommand()方法中:
Notification notification = new NotificationCompat.Builder(this, "CHANNEL")
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
.setContent(remoteViews)
.setSmallIcon(R.mipmap.ic_launcher)
.build();
startForeground(1, notification);
安卓8之后的版本中需要在前面设置消息渠道,notification中的渠道id必须要与notificationChanel中的id相同。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel("CHANNEL", getString(R.string.app_name), NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(getColor(R.color.black));
notificationChannel.enableVibration(false);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.createNotificationChannel(notificationChannel);
}
}
停止前台服务,参数代表是否删除通知栏上的通知:
stopForeground(true);