package com.fxy.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

import com.fxy.service.UploadJobService;

public class UploadAppCompat {
    private Activity mActivity;
    private JobScheduler mJobScheduler;
    private SensorManager mSensorManager;
    private SensorEventListener mSensorEventListener;
    private long lastMotionTime = 0L;

    public void startIdleDetection(Activity activity) {
        mActivity = activity;
        mSensorManager = (SensorManager) activity.getSystemService(Context.SENSOR_SERVICE);
        mSensorEventListener = new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent event) {
                // 检查传感器值的变化来判断设备是否空闲
                float[] values = event.values;
                long currentTime = System.currentTimeMillis();
                if (values[0] != 0 || values[1] != 0 || values[2] != 0) {
                    lastMotionTime = currentTime;
                } else if (currentTime - lastMotionTime > 60 * 1000) {
                    // 设备空闲 5 分钟后触发 job
                    triggerJob(mActivity);
                }
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {
                // 不需要实现
            }
        };

        Sensor sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        if (sensor != null) {
            mSensorManager.registerListener(mSensorEventListener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
        }
    }

    public void stopIdleDetection() {
        if (mSensorManager != null && mSensorEventListener != null) {
            mSensorManager.unregisterListener(mSensorEventListener);
        }
    }

    @SuppressLint("JobSchedulerService")
    public void triggerJob(Activity activity) {
        // 触发 job
        JobScheduler jobScheduler = (JobScheduler) activity.getSystemService(Context.JOB_SCHEDULER_SERVICE);
        ComponentName componentName = new ComponentName(activity, UploadJobService.class);
        JobInfo jobInfo = new JobInfo.Builder(101, componentName)
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                .setPersisted(true)
                .build();
        jobScheduler.schedule(jobInfo);
    }
}
