在 Android 中,我正在创建一个服务,它将监听传感器值的变化。但是每当我打开它时,我的应用程序就会不断崩溃。如果我删除线条
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
它工作正常
我创建了如下服务类:
public class CustomSensorService extends Service implements SensorEventListener{
static SensorManager sensorManager;
static Sensor mAccelerometer;
static Context mContext;
static final String LOG_TAG = "SimpleService";
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this,"Service Created",Toast.LENGTH_SHORT).show();
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
Log.d( LOG_TAG, "onSensorChanged" );
Toast.makeText(mContext,"Heelooo" , Toast.LENGTH_SHORT).show();
stopSelf();
}
}
我的活动为:
public class MainActivity extends Activity {
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = new Intent(this, CustomSensorService.class);
}
@Override
public void onResume(){
super.onResume();
startService(intent);
}
}
这是清单
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.learnandroidservice.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".CustomSensorService"/>
</application>
痕迹: