具有15秒延迟的处理程序仅在设备充电时才能正确工作

时间:2019-02-25 13:17:40

标签: android handler

我正在创建一个应用程序,我希望处理程序每​​15秒发送一次http请求。问题是,当我的设备(华为手表2)处于正常运行状态时,处理程序会按预期工作,但是当我将手表从充电器上取下时,这15秒会在15到40秒之间变化。我的实施过程有问题吗?我没有将任何Runnable传递给Handler,因为只有很少的工作要做。我有一个SensorHelper类,它仅获取心率值。在请求中,我将自定义消息对象作为JSON发送。

MainActivity

public class MainActivity extends WearableActivity {

    private static ConnectionService mService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.BODY_SENSORS)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.BODY_SENSORS},
                    1);
        }

        Intent intent = new Intent(this, ConnectionService.class);
        this.startService(intent);
        this.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

        setContentView(R.layout.activity_main);

        // Enables Always-on
        setAmbientEnabled();
    }

    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className,
                                       IBinder service) {
            ConnectionService.LocalBinder binder = (ConnectionService.LocalBinder) service;
            mService = binder.getServiceInstance();
            try {
                sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
        }
    };

    public static void sendMessage(String message) {
        mService.sendMessage(message);
    }
}

ConnectionService为了避免我的应用程序进入打ZE模式:

public class ConnectionService extends Service {

    private final IBinder mBinder = new LocalBinder();
    private static SensorHelper sensorHelper;
    private static OkHttpClient client = new OkHttpClient();
    public static final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");

    public class LocalBinder extends Binder {
        public ConnectionService getServiceInstance() {
            return ConnectionService.this;
        }
    }

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

    @Override
    public void onCreate() {
        if (sensorHelper == null) {
            sensorHelper = new SensorHelper(this);
        }
        super.onCreate();
        Intent notificationIntent = new Intent(this, MainActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);

        Notification notification = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("ASD")
                .setContentText("ASD")
                .setContentIntent(pendingIntent).build();

        startForeground(1337, notification);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        return START_REDELIVER_INTENT;
    }

    public void sendMessage(String message) {
        Message msg = new Message("HR", message);
        RequestBody requestBody = RequestBody.create(JSON, msg.toJson());

        Request request = new Request.Builder()
                .url("http://104.248.32.100/")
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }
            @Override
            public void onResponse(Call call, final Response response) throws IOException {
            }
        });

    }
}

SensorHelper以获得心率值并将其发布:

public class SensorHelper implements SensorEventListener {

    private String sensorValue = "normal";
    private static Handler handler = new Handler();
    private int delay = 15000;

    public SensorHelper(Context context) {
        SensorManager sensorManager = (SensorManager) context.getSystemService(SENSOR_SERVICE);
        Sensor heartRateSensor = sensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE);
        sensorManager.registerListener(this, heartRateSensor, SensorManager.SENSOR_DELAY_NORMAL);
        handler.postDelayed(new Runnable(){
            public void run() {
                sendMessage();
                handler.postDelayed(this, delay);
            }
        }, delay);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_HEART_RATE) {
            sensorValue = String.valueOf(event.values[0]);
        }
    }

    @Override
    public void onAccuracyChanged (Sensor sensor,int i){
    }

    private String getSensorValue() {
        return sensorValue;
    }

    private void sendMessage() {
        MainActivity.sendMessage(getSensorValue());
    }
}

在处理程序无法正常工作时,我是否犯了任何错误?是否需要传递Runnable来创建新线程?据阅读,处理程序正在创建一个新的线程

1 个答案:

答案 0 :(得分:0)

我也遇到了同样的问题,许多应用程序在设备不充电时在后台运行。问题是Android的电池优化。

解决方案非常简单,您必须通过转到设置>电池>电池优化(路径因制造商而异)来禁用应用程序的电池优化。

一些制造商还增加了一些额外的措施,通过减少定时任务的执行频率来优化电池,因此请检查可能会影响此任务的其他设置。

希望这会有所帮助!