Android(安卓)Service一前台服务(四)
16lz
2021-12-04
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()); }}
转载转载
更多相关文章
- Android(安卓)UI控件详解-Notification(通知)
- 【notification】Android(安卓)中创建状态栏通知
- Android通知Notification
- android中opengl es基本方法使用说明
- Android(安卓)- ScrollView 使用小计 里面嵌套的View 如何设置全
- Android(安卓)5.1 SystemUI-状态栏
- Build Variants Android变体构建配置
- Android(安卓)Notification 填充 自定义布局
- Android(安卓)实现拍照功能