应用程序也在后台和UI中运行



我正在做一个项目,我在传感器数据中读取并将它们发送到CSV文件。问题是,一旦应用程序在前端不再打开,应用程序就不再工作了。我读到我需要一些服务。问题是,我应该使用哪个服务,以及如何使用,以便我的传感器采集和写入CSV文件在应用程序未打开时也能工作,但也能够在用户界面上显示这些传感器数据中的一些?

如果应用程序完全关闭,它不需要再运行了,我想用一个按钮开始和停止这一切,就像在代码片段中看到的那样。我不确定前台服务是否正确。

可以看到如何构建应用程序的代码片段:

private SensorEventListener OrientSensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
OrientX = (int) sensorEvent.values[0];
OrientY = (int) sensorEvent.values[1];
OrientZ = (int) sensorEvent.values[2];
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//User Interface
time = findViewById(R.id.Time1);
//Steps UI
Stepstxt = findViewById(R.id.Stepstxt);
Walkingtxt = findViewById(R.id.Walkingtxt);
FastStepstxt = findViewById(R.id.FastStepstxt);
//Orientation UI
OrientXtxt = findViewById(R.id.OrientXtxt);
OrientYtxt = findViewById(R.id.OrientYtxt);
OrientZtxt = findViewById(R.id.OrientZtxt);
// Set Date for CSV File name and User Interface
Date currentTime = Calendar.getInstance().getTime();
String formattedDate = DateFormat.getDateInstance(DateFormat.FULL).format(currentTime);
time.setText(formattedDate);
// Initializing
SensorSwitch = findViewById(R.id.SensorSwitch);
//Sensor Initializing
//Acceleration
AccSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccelerometer = AccSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
//Amb Light
AmbLightSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAmbLight = AmbLightSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
//Orientation
OrientSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mOrientation = OrientSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
// Record Data to CSV and SwitchFlag
SensorSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b == true) {
// CSV Raw Data Open
Log.d(TAG, "Writing to " + getStorageDir());
try {
writer = new FileWriter(new File(getStorageDir(), "RawSensors_" + formattedDate + ".csv"));
} catch (
IOException e) {
e.printStackTrace();
}
//CSV Feature Data Open
Log.d(TAG, "Writing to " + getStorageDir());
try {
fwriter = new FileWriter(new File(getStorageDir(), "FeatureSensors_" + formattedDate + ".csv"));
} catch (
IOException e) {
e.printStackTrace();
}
SwitchFlag = true;
} else {
//CSV Raw Data Close
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
//CSV Feature Data Close
try {
fwriter.close();
} catch (IOException e) {
e.printStackTrace();
}
SwitchFlag = false;
}
}
});
}
// Next Activity
public void openMainActivity2(){
Intent intentMain2 = new Intent(this, MainActivity2.class);
startActivity(intentMain2);
}
// Start Sensor Events
protected void onResume() {
super.onResume();
AccSensorManager.registerListener(AccSensorEventListener, mAccelerometer, 1000000, 1000000);
AmbLightSensorManager.registerListener(AmbLightSensorEventListener, mAmbLight, 1000000, 1000000);
OrientSensorManager.registerListener(OrientSensorEventListener, mOrientation,1000000, 1000000);
}
protected void onPause() {
super.onPause();
AccSensorManager.unregisterListener(AccSensorEventListener);
AmbLightSensorManager.unregisterListener(AmbLightSensorEventListener);
OrientSensorManager.unregisterListener(OrientSensorEventListener);
}

// CSV File Creation
private String getStorageDir() {
return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
}
// CSV Write Function
private void CsvWrite(){
try {
writer.write(String.format("DateTime; %s;AccX; %f; AccY; %f; AccZ; %f; AccSum; %f; AmbLight; %d; OrientX; %d; OrientY; %d; OrientZ; %d n", dateTime, AccX, AccY, AccZ , AccSum, AmbLight, OrientX, OrientY, OrientZ));
}catch (IOException e) {
e.printStackTrace();
}
}
private void FeatureCsv(){
try {
fwriter.write(String.format("DateTime; %s; GoSteps; %d; RunSteps; %d; StepSum; %d; Position; %s; Location; %s n", dateTime, stepCount, RunCount, StepSum, position, location));
}catch (IOException e) {
e.printStackTrace();
}
}
private void FeatureCalc(){
// Step Calculation
if (AccChange > 40 && AccChange < 150){
stepCount++;
StepSum++;
} else if (AccChange > 150){
RunCount++;
StepSum++;
}
//Display Steps on UI
Stepstxt.setText("You have currently made: " + StepSum + " Steps");
Walkingtxt.setText("Thereof: " + stepCount + " Walking Steps");
FastStepstxt.setText("And: " + RunCount + " Faster Walking or Running Steps");
// Phone Orientation Feature
if(OrientY <= -5 && OrientY > -25){
position = "Standing";
}else if(OrientY <= -25 && OrientY >= - 90){
position = "Sitting";
}else if (OrientY <= -90 && OrientY >= -180 && AmbLight > 13){
position = "Laying";
}
else{
position = "None/NotUsed";
}
//Display Orientation on UI
OrientXtxt.setText("Azimuth: " + OrientX + "°");
OrientYtxt.setText("Pitch: " + OrientY + "°");
OrientZtxt.setText("Roll: " + OrientZ + "°");
// Location Feature
AbsOrient = Math.abs(OrientY);
if(AmbLight <= 13 && AbsOrient >= 60 && AbsOrient <= 120){
location = "Pocket";
}else if((AmbLight <= 13 && OrientY <= -170 && OrientY >= -190) || (OrientY > -5 && OrientY < 5)){
location = "Table";
}else if(AmbLight <= 25){
location = "Night/Indoor";
}else if(AmbLight > 25 && AmbLight <= 800){
location = "Day/Indoor";
}else if(AmbLight > 800){
location = "Day/Outside";
}else{
location = "None/Unknown";
}
}
}

对于任何类型的服务,你都可以使用intent或binding在activity和service之间进行通信。更多信息请点击这里

前台服务

前台服务执行了一些操作,这些操作被前台服务注意到用户。

前台服务将向用户显示一个通知,显示正在发生的事情,这里是您的测量值。点击这里了解更多信息。

例如,你可以允许用户从通知中停止测量。

后台服务

后台服务执行未被直接注意到的操作

如果你不想让你的用户知道你正在进行测量,那么可以使用后台服务。

然而,由于Android 8.0对后台服务的使用做了严格的限制,使得它很难使用。

WorkManager任务最近的一种方法是创建一个任务,如果您需要重复您的度量,它可以是周期性的,或者只使用WorkManager一次。

我建议你创建REST和UI应用程序,这样你的应用程序将从REST中读取数据,你的senor可以将数据发送到REST服务。

最新更新