我创建了一个记录加速度计值的应用程序,并将其存储在一个带有简单启动停止按钮的文件中。我想让它在屏幕关闭时继续工作,直到按下停止按钮,这是最好的方法。我被告知asyncTask但不确定我是否应该做全班。
public class StartAccelerometer extends Activity实现了SensorEventListener,OnClickListener {
private SensorManager SensorManager;
private Sensor Accelerometer;
TextView title,tvx,tvy,tvz;
EditText etshowval;
RelativeLayout layout;
private String acc;
private String read_str = "";
private final String filepath = "/mnt/sdcard/acc.txt";
private BufferedWriter BufferedWriter;
private BufferedReader BufferedReader;
private float x;
private float y;
private float z;
public static final int MSG_DONE = 1;
public static final int MSG_ERROR = 2;
public static final int MSG_STOP = 3;
private boolean running;
private Handler Handler;
private HandlerThread HandlerThread;
Button stop,start;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accelerometer);
SensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Accelerometer = SensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
SensorManager.registerListener(this, Accelerometer, android.hardware.SensorManager.SENSOR_DELAY_NORMAL);
//get layout
layout = (RelativeLayout) findViewById(R.id.relative);
//get textviews
title = (TextView)findViewById(R.id.name);
tvx = (TextView)findViewById(R.id.xval);
tvy = (TextView)findViewById(R.id.yval);
tvz = (TextView)findViewById(R.id.zval);
etshowval = (EditText)findViewById(R.id.showval);
title.setText("Accelerator");
HandlerThread = new HandlerThread("Working Thread");
HandlerThread.start();
Handler = new Handler(HandlerThread.getLooper());
Handler.post(Run);
start= (Button) findViewById(R.id.startAccel);
stop= (Button) findViewById(R.id.button2);
start.setOnClickListener(this);
stop.setOnClickListener(this);
}
private Runnable Run = new Runnable(){
@Override
public void run ()
{
while(true)
{
if (running)
{
try
{
WriteFile(filepath,acc);
}
catch (Exception e)
{
}
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
public void onClick(View view)
{
if(view.getId() == R.id.startAccel){
start();
}
else if(view.getId() == R.id.button2){
stop();
}
}
private synchronized void start()
{
running = true;
}
private synchronized void stop()
{
running = false;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
@Override
public void onSensorChanged(SensorEvent sensorEvent)
{
// TODO Auto-generated method stub
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
{
x = sensorEvent.values[0];
y = sensorEvent.values[1];
z = sensorEvent.values[2];
acc= String.valueOf(x) + ", " + String.valueOf(y) + ", " + String.valueOf(z);
tvx.setText("X = "+ String.valueOf(x));
tvy.setText("Y = "+ String.valueOf(y));
tvz.setText("Z = "+ String.valueOf(z));
}
}
public void CreateFile(String path)
{
File f = new File(path);
try {
Log.d("ACTIVITY", "Create a File.");
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String ReadFile (String filepath)
{
BufferedReader = null;
String tmp = null;
if (!FileIsExist(filepath))
CreateFile(filepath);
try
{
BufferedReader = new BufferedReader(new FileReader(filepath));
// Read string
while ((tmp = BufferedReader.readLine()) != null)
{
tmp += "\n";
read_str += tmp;
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return read_str;
}
public void WriteFile(String filepath, String str)
{
BufferedWriter = null;
if (!FileIsExist(filepath))
CreateFile(filepath);
try
{
BufferedWriter = new BufferedWriter(new FileWriter(filepath, true));
BufferedWriter.write(str);
BufferedWriter.newLine();
BufferedWriter.flush();
BufferedWriter.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public boolean FileIsExist(String filepath)
{
File f = new File(filepath);
if (! f.exists())
{
Log.e("ACTIVITY", "File does not exist.");
return false;
}
else
return true;
}
@Override
protected void onPause()
{
// TODO Auto-generated method stub
// mSensorManager.unregisterListener(this);
// Toast.makeText(this, "Unregister accelerometerListener", Toast.LENGTH_LONG).show();
//super.onPause();
super.onPause();
if (running == true) {
SensorManager.unregisterListener(this);
}
} }
答案 0 :(得分:0)
而不是活动使用服务:
On_start_service - >注册听众。
On_stop_service - >取消注册听众。
当你点击start_button启动服务并注册传感器时,直到你点击stop_button,加速计传感器继续监听传感器值的变化。如果单击stop_button,请取消注册侦听器并获取上次更新的值并停止服务。
您可以使用
手动启动和停止服务startService()
stopService()
在onStart()函数中,您可以添加要执行的实际功能。
该服务将继续在后台运行,直到您的活动终止。
有关服务的更多信息,请参阅http://developer.android.com/guide/components/services.html
答案 1 :(得分:0)
创建新服务,从单击start_button时的活动注册监听器并通过调用startService()启动服务 从单击stop_button时的活动中取消注册侦听器并使用stopService()停止服务。
即使屏幕关闭,服务仍会继续监听传感器的变化,您可以记录加速度计的值。
明确声明清单文件中的服务。