8.0开启服务

8.0版本开始不允许后台应用创建后台服务
代码借用自:https://blog.csdn.net/o279642707/article/details/82352431
ps:适配9.0服务,必须在AndroidManifest.xml文件中声明FOREGROUND_SERVICE权限(普通权限,声明系统会自动授予)

    private static final String UPLOAD_FILE = "com.nuoyuan.statistic.action.UPLOAD_FILE";
    private static String loadUrlPath = "";
    private static SttcHeadParams mHeadParams;
    public static final String CHANNEL_ID_STRING = "nyd001";
    @Override
    public void onCreate() {
        super.onCreate();
        //适配8.0service
        NotificationManager notificationManager = (NotificationManager) MyApp.getInstance().getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel mChannel = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            mChannel = new NotificationChannel(CHANNEL_ID_STRING, "诺秒贷", NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(mChannel);
            Notification notification = new Notification.Builder(getApplicationContext(), CHANNEL_ID_STRING).build();
            startForeground(1, notification);
        }
    }

    public UploadFilesIntentService() {
        super("UploadFilesIntentService");
    }

    public static void startActionFoo(Context context, String loadPath, SttcHeadParams headParams) {
        Intent intent = new Intent(context, UploadFilesIntentService.class);
        intent.setAction(UPLOAD_FILE);
        mHeadParams = headParams;
        loadUrlPath = loadPath;
//开启服务兼容
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            context.startForegroundService(intent);
        } else {
            context.startService(intent);
        }
    }

……
……
…….
}

你可能感兴趣的:(8.0开启服务)