[如何在Android中检测设备抖动。要使用哪个Android服务?

问题描述 投票:1回答:1

我想检测设备的摇晃手势。晃动时,应发出警报。我想为此提供服务,但是我为该使用哪种服务感到困惑。

android android-service
1个回答
1
投票

您可以使用Accelerometer传感器检测设备的移动。以下是实现

public class ShakerService extends Service {

    public static final String TAG = "ShakerService";
    private Shaker mShaker;


    @Override
    public void onCreate() {
        super.onCreate();
        getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
        Log.d(TAG,"Starting service : onCreate()");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG,"iniciando");
        mShaker = new Shaker(this);
        mShaker.setOnShakeListener(new Shaker.OnShakeListener() {

            @Override
            public void onShake() {
                Toast.makeText(getApplicationContext(),"here", Toast.LENGTH_SHORT);
                Log.d(TAG,"OnShake");
            }
        });

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notifyit();
        }
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        mShaker.pause();
        super.onDestroy();
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private String createNotificationChannel(String channelId, String channelName) {
        Log.d(TAG,"Notification channel is creating");
        NotificationChannel chan = new NotificationChannel(channelId,
                channelName, NotificationManager.IMPORTANCE_NONE);

        NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            service.createNotificationChannel(chan);

        return channelId;
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public void notifyit() {

        Log.d(TAG,"Notification starting");
        Intent i = new Intent(this, SegmentTesterAct.class);
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
        String notificationChannel = createNotificationChannel("shakeitoff", "shakeitoff");
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, notificationChannel);

        Notification notification = builder.setContentIntent(pi)
                .setSmallIcon(R.drawable.nextome).setTicker("shake").setWhen(System.currentTimeMillis())
                .setAutoCancel(true).setContentTitle(getText(R.string.app_name))
                .setContentText(getText(R.string.intro)).build();
        startForeground(1337, notification);
    }

}
public class Shaker implements SensorListener , SensorEventListener {
    public static float xShake = 0.0f;
    public static float yShake = 0.0f;
    public static float zShake = 0.0f;

    public static final float NOISE = 0.01f;
    public static final float OLDMIN = -10f;
    public static final float OLDMAX = 10;
    public static final float NEWMIN = 0;
    public static final float NEWMAX = 1;

    private static final int BASE_FORCE_THRESHOLD = 350;
    private static final int TIME_THRESHOLD = 200;
    private static final int SHAKE_TIMEOUT = 500;
    private static final int SHAKE_DURATION = 1000;
    private static final int SHAKE_COUNT = 3;

    private SensorManager mSensorMgr;
    private float mLastX = -1.0f, mLastY = -1.0f, mLastZ = -1.0f;
    private long mLastTime;
    private OnShakeListener mShakeListener;
    private Context mContext;
    private int mShakeCount = 0;
    private long mLastShake;
    private long mLastForce;
    private SharedPreferences preferences;

    public Shaker(Context context) {
        mContext = context;
        preferences = context.getSharedPreferences("shakeitoff", context.MODE_PRIVATE);
        resume();
    }

    public void setOnShakeListener(OnShakeListener listener) {
        mShakeListener = listener;
    }

    public void resume() {
        mSensorMgr = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
        if (mSensorMgr == null) {
            throw new UnsupportedOperationException("Sensors not supported");
        }
        boolean supported = mSensorMgr.registerListener(this, SensorManager.SENSOR_ACCELEROMETER, SensorManager.SENSOR_DELAY_GAME);
        if (!supported) {
            mSensorMgr.unregisterListener(this, SensorManager.SENSOR_ACCELEROMETER);
            throw new UnsupportedOperationException("Accelerometer not supported");
        }
    }

    public void onAccuracyChanged(int sensor, int accuracy) {
    }

    public void pause() {
        if (mSensorMgr != null) {
            mSensorMgr.unregisterListener(this, SensorManager.SENSOR_ACCELEROMETER);
            mSensorMgr = null;
        }
    }

    public void onSensorChanged(int sensor, float[] values) {
        if (sensor != SensorManager.SENSOR_ACCELEROMETER) return;
        long now = System.currentTimeMillis();

        values[SensorManager.DATA_X] = -values[SensorManager.]
        boolean preX =false;
        boolean preY =false;
        float xDiff = (mLastX - values[SensorManager.DATA_X]);
        float yDiff = (mLastY - values[SensorManager.DATA_Y]);
        float zDiff = (mLastZ - values[SensorManager.DATA_Z]);

         //Based on xDiff, yDiff, zDiff you can detect shaking 
         mLastX = values[SensorManager.DATA_X];
         mLastY = values[SensorManager.DATA_Y];
         mLastZ = values[SensorManager.DATA_Z];



 }

    @Override
    public void onSensorChanged(SensorEvent event) {

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    public interface OnShakeListener {
        public void onShake();
    }

}

您需要像这样启动ShakerService

startService(new Intent(this, ShakerService.class));来自您的活动

© www.soinside.com 2019 - 2024. All rights reserved.