public class WeatherSerVice extends Service {
private static final int NOTIFICATION_ID = 234;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
//如果API在26以上即版本为O则调用startForefround()方法启动服务
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
createNotificationChannel();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// return START_STICKY;
return START_STICKY_COMPATIBILITY;
}
//Channel ID 必须保证唯一
private static final String CHANNEL_ID = "com.appname.notification.channel";
/**
* 创建通知渠道
*/
@RequiresApi(api = Build.VERSION_CODES.O)
private void createNotificationChannel() {
//设定的通知渠道名称
String channelName = getString(R.string.channel_name);
//设置通知的重要程度
int importance = NotificationManager.IMPORTANCE_LOW;
//构建通知渠道
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, channelName, importance);
channel.setDescription("按时大苏打实打实");
//在创建的通知渠道上发送通知
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);
builder.setSmallIcon(R.drawable.ic_launcher_background) //设置通知图标
.setContentTitle("标题")//设置通知标题
.setContentText("内容")//设置通知内容
.setAutoCancel(true) //用户触摸时,自动关闭
.setOngoing(true);//设置处于运行状态
//向系统注册通知渠道,注册后不能改变重要性以及其他通知行为
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
//将服务置于启动状态 NOTIFICATION_ID指的是创建的通知的ID
startForeground(NOTIFICATION_ID, builder.build());
}
}
转载转载