如何在Service

时间:2017-04-04 14:13:29

标签: android multithreading

我想使用服务中的线程将传感器连续数据存储在数据库中。 这是我的代码

我的活动代码:

    public class TrackingActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tracking);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    Intent i = new Intent(this, TrackService.class);
    startService(i);

    }
 }

服务类代码:

    public class TrackService extends Service implements SensorEventListener {

private SensorManager mSensorManager;
private Sensor mSensor;

double ax, ay, az;

@Override
public void onCreate() {
    super.onCreate();

    mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
    mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);


    if (mSensor != null) {
        mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
    } else {

        stopSelf();
    }
}

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public void onSensorChanged(SensorEvent event) {

    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        ax = event.values[0];
        ay = event.values[1];
        az = event.values[2];
    }
}

@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
}

}

由于我是Android的新手,我不知道如何在服务中创建线程以将Accelerometer的数据连续存储在数据库或文件中。

0 个答案:

没有答案