0

您好,我是 android 编程新手。我正在为学校编写一个应用程序,我需要将加速度计数据保存到一个 txt 文件中。问题是当我锁定屏幕或打开屏幕保存时,数据记录会停止。你能给我建议吗?

这是我的代码:

package emzet.data2text;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.view.View;
import android.widget.Button;

import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;


public class MainActivity extends Activity implements SensorEventListener {

private SensorManager sensorManager;
private Sensor accelerometer;
private FileWriter writer;
private Button btnStart, btnStop;
String root = Environment.getExternalStorageDirectory().toString();

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnStart = (Button) findViewById(R.id.btnStart);
    btnStop = (Button) findViewById(R.id.btnStop);
    btnStart.setEnabled(true);
    btnStop.setEnabled(true);
    //PowerManager mgr = (PowerManager)this.getSystemService(Context.POWER_SERVICE);
    //PowerManager.WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK |         PowerManager.ACQUIRE_CAUSES_WAKEUP, "MyWakeLock");


    sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}

public void onStartClick(View view) {
    sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
    btnStop.setEnabled(true);
    btnStart.setEnabled(false);

}

public void onStopClick(View view) {
    sensorManager.unregisterListener(this);
    btnStart.setEnabled(true);
    btnStop.setEnabled(false);
}
protected void onResume() {
    super.onResume();
    try {
        writer = new FileWriter(root + "/acc2txt-file.txt",true);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

protected void onPause() {
    super.onPause();
    if(writer != null) {
        try {
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}



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

}

@Override
public void onSensorChanged(SensorEvent event) {

    float x = event.values[0];
    float y = event.values[1];
    float z = event.values[2];
    SimpleDateFormat time = new SimpleDateFormat("HH:mm:ss:SSS");
    String s = time.format(new java.util.Date());
    try {
        writer.write(s+"\t"+x+"\t"+y+"\t"+z+"\n");
    } catch (IOException e) {
        e.printStackTrace();
    }

}

}
4

1 回答 1

2

如果您还想在应用停止中保存数据,您可以使用 START_STICKY 选项编写服务,即使应用被终止,该服务也会保持活动状态。这是 STICKY 服务的示例,它很容易并且适合您的需求示例 1 示例 2

public class MyService extends Service {

protected String messageData = null;
public static final int MSG_REGISTER_CLIENT   = 1;
public static final int MSG_UNREGISTER_CLIENT = 2;
public static final int MSG_CUSTOM_TYPE       = 3;

@Override public void onCreate() {

    super.onCreate();

    MyServiceRunningBackground();


    running = true;

}



@Override public int onStartCommand(Intent intent, int flags, int startId) {

    return START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
    //TODO for communication return IBinder implementation
    return null;
}


@Override public boolean onUnbind(Intent intent) {

    return super.onUnbind(intent);
}

@Override public void onRebind(Intent intent) {

    super.onRebind(intent);
}

@Override public void onDestroy() {

    super.onDestroy();

    running = false;
}


private void MyServiceRunningBackground() {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
    {
        final int restartAlarmInterval = 6000;
        final int resetAlarmTimer = 2*1000;
        final Intent restartIntent = new Intent(this, esService.class);
        restartIntent.putExtra("ALARM_RESTART_SERVICE_DIED", true);
        final AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        Handler restartServiceHandler = new Handler()
        {
            @Override
            public void handleMessage(Message msg) {
                PendingIntent pintent = PendingIntent.getService(getApplicationContext(), 0, restartIntent, 0);
                alarmMgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + restartAlarmInterval, pintent);
                sendEmptyMessageDelayed(0, resetAlarmTimer);
            }
        };
        restartServiceHandler.sendEmptyMessageDelayed(0, 0);
    }
}




private static final String TAG = "MyService";

}

创建这个新服务并在您的情况下执行您想要执行的工作,在您的应用程序后台保存数据,即使您的应用程序被杀死,只需启动此服务,就像您在活动的 onCreate 中打开新意图一样。之后,即使用户杀死应用程序,该服务也将处于活动状态。像这样启动这个服务

  Intent intent = new Intent(MyActivity.this, MyService.class);
    startService(intent);

我希望我清楚

于 2014-11-01T21:29:29.303 回答