我想創建一個應用程序,在主線程仍在工作時,我的傳感器在另一個線程中獲取值。我嘗試了另一個線程,但它沒有工作。我嘗試了一個服務和一個IntentService,但傳感器在主線程之後啓動。我目前的代碼是這樣的。Android傳感器和線程
MyService.java
public class MyService extends IntentService implements SensorEventListener
{
public MyService()
{
super("MyService");
}
Sensor mLight;
SensorManager mSensorManager;
float max;
float currentLux;
float currentProx;
@Override
public IBinder onBind(Intent intent)
{
Log.d("Service", "On bind");
return null;
}
@Override
public void onCreate()
{
Log.d("Service", "On create");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event)
{
if(event.sensor.getType() == Sensor.TYPE_LIGHT)
{
currentLux=(int) event.values[0];
float perc=(float) ((currentLux*100)/max);
Log.d("Light", String.valueOf(perc));
}
else if(event.sensor.getType() == Sensor.TYPE_PROXIMITY)
{
currentProx=(int) event.values[0];
Log.d("Proximity", String.valueOf(currentProx));
}
}
@Override
public void onDestroy()
{
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
Log.d("Service", "On stop");
mSensorManager.unregisterListener(this);
}
@Override
public void onStart(Intent intent, int startid)
{
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
Log.d("Service", "On start");
}
@Override//here u should register sensor and write onStartCommand not onStart
public int onStartCommand(Intent intent, int flags, int startId)
{
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mSensorManager.registerListener(this, mSensorManager
.getDefaultSensor(Sensor.TYPE_LIGHT),
SensorManager.SENSOR_DELAY_FASTEST);
mLight = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
mSensorManager.registerListener(this, mSensorManager
.getDefaultSensor(Sensor.TYPE_PROXIMITY),
SensorManager.SENSOR_DELAY_FASTEST);
max=mLight.getMaximumRange();
Log.d("MAX=", String.valueOf(max));
return Service.START_STICKY;
}
@Override
protected void onHandleIntent(Intent intent)
{
}
}
Listeners.java
public class Listeners extends Activity implements OnClickListener
{
Button button0;
Intent listenersIntent;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.listeners);
lista= new ArrayList<Float>();
button0 = (Button) findViewById(R.id.button0);
button0.setOnClickListener(this);
listenersIntent = new Intent(this, MyService.class);
startService(listenersIntent);
for (int i=0; i<999; i++)
Log.d("Main", String.valueOf(i));
}
@Override
public void onClick(View arg0)
{
stopService(listenersIntent);
}
}
我的問題是,我總是得到1-999之前的任何接近/光值,而我希望他們能一起運行。你能幫我嗎?
如果你打算重寫onstart和oncreate它,你爲什麼要擴展intentservice? – njzk2
我刪除了這兩種方法,但在傳感器啓動前我總是得到1-999 –
不能發佈日誌嗎? – njzk2