<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

写个public class NetWorkService extends Service ,然后在onCreate里面写上如下代码。
如果想点击通知,打开某个Activity 把注释代码打开
// PendingIntent pendingIntent =PendingIntent.getActivity(this, 0, intent, 0);
// builder1.setContentIntent(pendingIntent);

        // 设置事件信息,点击通知可以跳转到指定Activity
        Intent intent = new Intent(this, SelectMoShiActivity.class);

        NotificationChannel chan = new NotificationChannel("toca",
                "toca2", NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(chan);

//        // 设置事件信息,点击通知可以跳转到指定Activity
//        NotificationManager notificationManager = (NotificationManager)
//                getSystemService(Context.NOTIFICATION_SERVICE);

        // 设置通知显示相关信息
        Notification.Builder builder1 = new Notification.Builder(this,"toca");
        builder1.setSmallIcon(R.mipmap.ic_launcher); //设置图标
        /*builder1.setTicker("显示第二个通知");*/
        builder1.setContentTitle(null); //设置标题
        builder1.setContentText("Toca Run..."); //消息内容
        builder1.setWhen(System.currentTimeMillis()); //发送时间
        builder1.setDefaults(Notification.DEFAULT_ALL); //设置默认的提示音,振动方式,灯光
        builder1.setAutoCancel(true);//打开程序后图标消失

        // 延时意图,所谓延时意图就是不是马上执行,需要用户去点击后才执行,其实就是对Intent对封装
//        PendingIntent pendingIntent =PendingIntent.getActivity(this, 0, intent, 0);
//        builder1.setContentIntent(pendingIntent);
        Notification notification1 = builder1.build();
        notificationManager.notify(124, notification1); // 通过通知管理器发送通知
        // id=通知到唯一标示  notification=通知
        startForeground(1, notification1);

然后开启service

        Intent intent2 = new Intent(context, NetWorkService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(intent2);  //使用bindservice也可以
        } else {
            context.startService(intent2);
        }
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐