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

问题描述 投票:0回答:1

我正在创建一个应用程序,我希望Handler每15秒发送一次http请求。问题是,虽然我的设备(华为手表2)处于chare状态,但Handler可以正常工作,但当我将手表从充电器上取下时,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为了避免我的申请进入DOZE模式:

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());
    }
}

我正在制作什么错误,而Handler工作不正常?是否需要传递一个Runnable来创建一个新线程?据我所知,Handler正在创建一个新的Thread

android handler
1个回答
0
投票

我遇到了同样的问题,当设备没有充电时,很多应用程序都在后台运行。问题是Android的电池优化。

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

一些制造商还通过减少定时任务的处理来增加额外的措施来优化电池,因此请检查可能会影响这一点的额外设置。

希望这可以帮助!

© www.soinside.com 2019 - 2024. All rights reserved.