0
我寫了類似這樣的東西,我可以運行它,但它不工作。有人幫忙嗎?請耐心等待:D 當手機被鎖定時,我需要保存來自加速計的數據,並將其放入口袋中。 感謝來自鎖定手機的數據
MainActivity:
package emzet.acc2txt;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private Button btnStart, btnStop;
@Override
protected 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);
}
public void onStartClick(View view) {
startService(new Intent(this,accService.class));
btnStop.setEnabled(true);
btnStart.setEnabled(false);
}
public void onStopClick(View view) {
stopService(new Intent(this, accService.class));
btnStart.setEnabled(true);
btnStop.setEnabled(false);
}
}
爲MyService:
package emzet.acc2txt;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Environment;
import android.os.IBinder;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
public class accService extends Service implements SensorEventListener{
String root = Environment.getExternalStorageDirectory().toString();
protected static SensorManager sensorManager;
protected static Sensor accelerometer;
private FileWriter writer;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate(){
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
@Override
public void onDestroy(){
if(writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
sensorManager.unregisterListener(this);
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
writer = new FileWriter(root + "/pokus.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
return START_STICKY;
}
@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();
}
}
}
任何幫助嗎? 我當然編輯了清單...
您可能需要一個部分喚醒鎖,但請注意它會耗盡您的電池來完成此操作。 – 2014-11-03 02:24:48
當手機未鎖定時,此代碼甚至無法使用。 我不知道我是否在我的代碼中沒有任何錯誤。它的工作原理是什麼? 我是新來的android和java,這是我的第二個應用程序:/ – Mirko 2014-11-03 08:56:21