1.小米跑步机传感器简介
当手机放置在跑步机上时,收集手机中传感器的数据,判断是否在跑步机上运动,若运动一步则跑步机传感器上报一次数据1,不运动则不报。
2.将跑步机数据集成到计步器数据库
2.1.通知系统服务
在注册或者解除注册跑步机传感器的时候通过Binder告知系统服务。 这步骤为必须操作,否则跑步机计步器数据无法同步至系统计步数据库。
代码示例:
public class MainActivity extends AppCompatActivity {
private SensorManager mSensorManager;
private Sensor mTreadmillSensor;
private TreadmillListener mTreadmillListener;
private static final int TREADMILL_SENSOR = 33171041;
private static final String SERVICE_NAME = "miui_step_counter_service";
private Binder mBinder;
@RequiresApi(api = Build.VERSION_CODES.Q)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mTreadmillSensor = mSensorManager.getDefaultSensor(TREADMILL_SENSOR,true);
mTreadmillListener = new TreadmillListener();
//监听跑步机Sensor
mSensorManager.registerListener(mTreadmillListener,mTreadmillSensor,mSensorManager.SENSOR_DELAY_NORMAL);
//通知系统服务,注册的时候发送true
sendMessage(true);
}
@RequiresApi(api = Build.VERSION_CODES.Q)
public void sendMessage(boolean is){
//获取系统服务,ServiceManager报错底下有解决方案
IBinder binder = ServiceManager.getService(SERVICE_NAME);
if (mBinder == null) {
mBinder = new Binder();
}
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
data.writeInterfaceToken("miui_step_counter_service");
data.writeBoolean(is);
//传过去一个全局Binder(为了感知本类是否被销毁)
data.writeStrongBinder(mBinder);
try {
binder.transact(0,data,reply,0);
} catch (RemoteException e) {
e.printStackTrace();
}
}
private class TreadmillListener implements SensorEventListener{
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
}
@Override
public void onAccu网页生成app软件racyChanged(Sensor sensor, int i) {
}
}
@RequiresApi(api = Build.VERSION_CODES.Q)
@Override
protected void onDestroy() {
super.onDestroy();
//解注册的时候,通知系统服务,发送false
mSensorManager.unregisterListener(mTreadmillListener,mTreadmillSensor);
sendMessage(false);
}
}
2.2.ServiceManager拿不到解决方案
在代码中创建一个包名为android.os,类名为ServiceManager的类。
代码示例:
package android.os;
public class ServiceManager {
private ServiceManager(){}
public static IBinder getService(String name){
return null;
}
}
2.3.说明
目前跑步机计步传感器支持小米12、小米12 Pro、小米12S Pro、小米12S Ultra四款机型,如果您的应用在注册下面这个特定传感器type时返回的sensor对象为空,说明当前机型不支持跑步机计步传感器,应用可通过此sensor对象的返回值来判定该功能是否生效。
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mTreadmillSensor = mSensorManager.getDefaultSensor(TREADMILL_SENSOR,true);
//根据mTreadmillListener是否为空来判定当前手机是否支持跑步机计步的功能
mTreadmillListener = new Trh5生成appeadmillListener();
编辑:yimen,如若转载,请注明出处:https://www.yimenapp.com/kb-yimen/12526/
部分内容来自网络投稿,如有侵权联系立删