Android重力感应模拟器实现与实例开发(转)

原址http://wxmijl.blog.163.com/blog/static/13245928201062734631474/

SensorSimulator是重力感应模拟器,下载地址如下:

http://code.google.com/p/openintents/downloads/detail?name=sensorsimulator-1.0.0-beta1.zip&can=2&q=

在你的就应用里怎样使用SensorSimulator

如果你从没使用过,请在你的模拟器中安装OpenIntents.apk

AddtheexternalJARopenintents-lib-n.n.n.jarintoyourproject.

ReplacethefollowingcodeinonCreate():

mSensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);

bythiscode

//BeforecallinganyoftheSimulatordata,

//theContentresolverhastobeset!!

Hardware.mContentResolver=getContentResolver();

//LinksensormanagertoOpenIntentsSensorsimulator

mSensorManager=(SensorManager)newSensorManagerSimulator((SensorManager)

getSystemService(SENSOR_SERVICE));

Bydefaultthisstillpassestheoriginalsensorvalues,sotoactivatesensorsyouhavetofirstcall(tosetthesensorsettings):

Intentintent=newIntent(Intent.ACTION_VIEW,

Hardware.Preferences.CONTENT_URI);

startActivity(intent);

andthen

//firstdisablethecurrentsensor

mSensorManager.unregisterListener(mGraphView);

//nowconnecttosimulator

SensorManagerSimulator.connectSimulator();

//nowenablethenewsensors

mSensorManager.registerListener(this,

SensorManager.SENSOR_ACCELEROMETER|

SensorManager.SENSOR_MAGNETIC_FIELD|

SensorManager.SENSOR_ORIENTATION,

SensorManager.SENSOR_DELAY_FASTEST);

Allothercodestaysuntouched.YoucanfindreferencecodeforhowtoimplementsensorsintheAPIdemos/OS/Sensors.java.

Usuallyonewould(un)registerthesensorsinonResume()andonStop():

@Override

protectedvoidonResume(){

super.onResume();

mSensorManager.registerListener(this,

SensorManager.SENSOR_ACCELEROMETER|

SensorManager.SENSOR_MAGNETIC_FIELD|

SensorManager.SENSOR_ORIENTATION,

SensorManager.SENSOR_DELAY_FASTEST);

}

@Override

protectedvoidonStop(){

mSensorManager.unregisterListener(mGraphView);

super.onStop();

}

ThenjustimplementthestandardAndroidSensorListener(thereisnoOIcounterpartnecessary).

classMySensorActivityextendsActivityimplementsSensorListener{

publicvoidonSensorChanged(intsensor,float[]values){

//dosomethingwiththesensorvalues.

}

}

Note1:TheOpenIntentsclassSensorManagerSimulatorisderivedfromtheAndroidclassSensorManagerandimplementsexactlythesamefunctions(seeAndroidSensorManager).Forthecallback,thestandardAndroidSensorListenerisused.TheonlynewfunctionsareconnectSimulator()anddisconnectSimulator().

Note2:Wheneveryouarenotconnectedtothesimulator,youwillgetrealdevicesensordata:theorg.openintents.hardware.SensorManagerSimulatorclasstransparentlycallstheSensorManagerreturnedbythesystemserviceinthiscase.

相关推荐