android 8.0对服务的限制

android 8.0以后 不再支持后台运行服务了,

所以如果想暂时的适配之前的工程

可以修改targetSdkVersion到26以下版本

targetSdkVersion 25

如果想正儿八经的适配

可以通过启动前台服务来启动

前台服务依然不能依然不能做后台的事情

    public static void startMyService(Context content, Intent intent) {
//        content.startService(intent);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //android8.0以上通过startForegroundService启动service
            content.startForegroundService(intent);
        } else {
            content.startService(intent);
        }
    }

而且服务启动5s内 必须得调用

startForeground

方法

我这边来一个简单的封装

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void createNotificationChannel(int i) {
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        // 通知渠道的id
        String id = "my_channel_01";
        // 用户可以看到的通知渠道的名字.
        CharSequence name = getString(R.string.app_name);
//         用户可以看到的通知渠道的描述
        String description = getString(R.string.app_desc);
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel mChannel = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            mChannel = new NotificationChannel(id, name, importance);
        }
//         配置通知渠道的属性
        mChannel.setDescription(description);
//         设置通知出现时的闪灯(如果 android 设备支持的话)
        mChannel.enableLights(true);
        mChannel.setLightColor(Color.RED);
//         设置通知出现时的震动(如果 android 设备支持的话)
        mChannel.enableVibration(true);
        mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
//         最后在notificationmanager中创建该通知渠道 //
        mNotificationManager.createNotificationChannel(mChannel);

        // 为该通知设置一个id
        int notifyID = 1;
        // 通知渠道的id
        String CHANNEL_ID = "my_channel_01";
        // Create a notification and set the notification channel.
        String content = "前台通知内容";
        Notification notification = new Notification.Builder(this)
                .setContentTitle(getResources().getString(R.string.app_name)).setContentText(content)
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setChannelId(CHANNEL_ID)
                .build();
        startForeground(1, notification);
    }

可以在service中的

onStartCommand

中调用


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createNotificationChannel(i);
        }

后台服务的替代品暂时还没找到。有人说可以使用

public class TestJobService extends JobService

但是又有人说这个JobService服务只能后台运行10分钟 那根本就不够用的

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安果移不动

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值