在Android中监控传感器值以触发通知,然后关闭传感器服务

时间:2014-12-04 06:41:02

标签: android service accelerometer android-sensors

我正在尝试通过服务监控Android中的传感器值,如果传感器的值有任何变化(加速度计)......它应该触发通知,然后服务应该自动停止... 但最新发生的事情是该服务不会停止,它会不断发出通知。

有人能提出更好的方法吗?

  

传感器服务

public class Sensored extends Service implements SensorEventListener {

SensorManager ssrmgr = null;
Sensor ssr = null;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    ssrmgr = (SensorManager) getSystemService(SENSOR_SERVICE);
    ssr = ssrmgr.getDefaultSensor(Sensor.TYPE_SIGNIFICANT_MOTION);
    ssrmgr.registerListener(this, ssr,SensorManager.SENSOR_DELAY_NORMAL);

    return START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onSensorChanged(SensorEvent event) {
    // TODO Auto-generated method stub
    float value = event.values[0];
    if(value>0)
    {
        Intent i=new Intent();
        i.setClass(this, NotifyActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        ssrmgr.unregisterListener(this);
        stopSelf();
        startActivity(i);
    }


}

protected void onPause()
{
    stopService(new Intent(getApplicationContext(), Sensored.class));
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
    // TODO Auto-generated method stub

}

}

  

通知类

公共类NotifyActivity扩展了ActionBarActivity {

 @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
         super.onCreate(savedInstanceState);

            // Build notification
            // Actions are just fake
            Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            NotificationCompat.Builder noti = new NotificationCompat.Builder(this)
                .setContentTitle("Inspire Me")
                .setSmallIcon(R.drawable.ic_launcher)
                .setSound(alarmSound);
            noti.setAutoCancel(true);
            NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
            // hide the notification after its selected

            notificationManager.notify(001, noti.build());  
    }

}

0 个答案:

没有答案