后台保活方案之前台 service

设置点击事件 , 点击启动服务

 Intent i = new Intent(context, LongRunningService.class);
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
       context.startForegroundService(i);
   } else {
       context.startService(i);
   }

服务类

class LongRunningService extends Service {

    private static final int NOTICE_FG_ID = 2;
    private Notification notification;
    private Context context;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        
		//开启前台服务
        startForeground(NOTICE_FG_ID, getNotification());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        //业务逻辑
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println( <=网络 ----后台保活----- wifi=>");
            }
        }, 1000, 1000 * 10);
         //业务逻辑结束

        return START_STICKY;
    }

    public Notification getNotification() {

        //1:获取系统提供的通知管理服务
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification.Builder builder = new Notification.Builder(this);

        //2:如果是8以上的系统,则新建一个消息通道,传一个channelId
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = "测试";//消息通道的id,以后可以通过该id找到该消息通道
            String channelName = "测试通知";//消息通道的name
            // 通知的优先级,作用就是优先级的不同。可以导致消息出现的形式不一样。
            // HIGH是会震动并且出现在屏幕的上方。设置优先级为low或者min时。来通知时都不会震动,且不会直接出现在屏幕上方
            NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(channel);
            builder.setChannelId(channelId);
        }

        Intent intent = new Intent(this, ServiceLifeActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("我测试")
                .setContentText("请不要关闭我!")
//                .setContentText(TimeUtil.getNowMDHMSTime())
                .setWhen(System.currentTimeMillis())
                .setContentIntent(pendingIntent);

        Notification notification = builder.build();
        notification.flags = Notification.FLAG_ONGOING_EVENT; // 设置常驻,不能滑动取消

        return notification;
    }
    }

注册service

动态或静态注册
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值