是您必須在背景中運行服務以及接近傳感器輸入,以獨立於您的前臺應用程序使用它。下面的代碼顯示在後臺
public class PocketService extends Service implements SensorEventListener {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_SHORT).show();
Log.d("TAG", "onCreate");
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
mSensorManager.registerListener(this, mProximity,
SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_SHORT).show();
Log.d("TAG", "onDestroy");
mSensorManager.unregisterListener(this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_SHORT).show();
Log.d("TAG", "onStart");
return START_STICKY;
}
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
if (sensor.getType() == Sensor.TYPE_PROXIMITY) {
distance = event.values[0];
if (distance < 1) {
enableScreenLock();
} else {
disableScreenLock();
}
}
}
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
}
你必須從活動開始這一點,直到任務管理器殺它,它會在你的後臺運行,由於時間緊內存不足運行的服務。但是它會嘗試在內存可用時重新創建它的實例,因爲onStartCommand()方法返回START_STICKY。
您是否嘗試在服務中註冊此偵聽器? – Huang 2012-02-10 07:49:43