其他分享
首页 > 其他分享> > Android Wear:它如何在活动生命周期中发挥作用?

Android Wear:它如何在活动生命周期中发挥作用?

作者:互联网

我制作了一个带有活动的可穿戴应用.

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.i("WEAR", "CREATE");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
    stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
        @Override
        public void onLayoutInflated(WatchViewStub stub) {
            mTextView = (TextView) stub.findViewById(R.id.text);
        }
    });
    SensorManager  sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    Sensor hrs = sm.getDefaultSensor(Sensor.TYPE_HEART_RATE);
    sm.registerListener(hrListener, hrs, 3);

    if (savedInstanceState != null) {
        Log.i("WEAR", "RESTORE");
        // ... get previous sensor data from the bundle

    }
}

@Override
protected void onStop() {
    Log.i("WEAR", "STOP");
    super.onStop();
    sm.unregisterListener(hrListener, hrs);
}

@Override
protected void onDestroy() {
    Log.i("WEAR", "DESTROY");
    super.onDestroy();
}

@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
    Log.i("WEAR", "SAVE");
    // ... save sensor data in the bundle
    super.onSaveInstanceState(savedInstanceState);
}

private SensorEventListener hrListener = new SensorEventListener() {
    @Override
    public void onSensorChanged(final SensorEvent event) {
        final float hearRate = event.values[0];
        Log.i("SENSOR", hearRate);
        mTextView.setText(Float.toString(hearRate));
    }

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

    }
};

启动时,我会看到来自传感器的数据流.
片刻之后,屏幕返回到时钟表面,并且日志在我的应用程序调试流程中显示“ STOP”和“ SAVE”.我重新启动了该应用程序,但捆绑包为空,丢失了所有保存在捆绑包中的数据. onDestroy从未被调用过,为什么我没有得到任何捆绑包?
这是一个Gear Live.

解决方法:

关闭磨损应用的动作应从左向右滑动以将其关闭.您将看到onDestroy被调用.
如果您仅按一下按钮(我只有moto 360第一代,即侧面按钮),就好像将应用程序置于前台.因此,仅调用了onStop和onStart对.希望这个较晚的答案对您有所帮助.

标签:android-sensors,wear-os,android-activity,activity-lifecycle,android
来源: https://codeday.me/bug/20191120/2041267.html