安卓:在摇监听器类使用共享preferences [英] Android: Using SharedPreferences in a Shake Listener Class

查看:157
本文介绍了安卓:在摇监听器类使用共享preferences的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我是pretty新的Andr​​oid和编程一般,所以请去容易;-)
其次,我认为这个网站是一个救星!
好了,现在到问题的肉...

First, I'm pretty new to Android and programming in general, so please go easy ;-) Second, I think this site is a lifesaver! OK, now on to the meat of the issue...

在我的努力,试图了解更多关于Android开发,并使用用户preferences我创建了一个小应用程序工作正常,并有一定数量的用户可以改变,使它看起来不同的选择。不过,我碰到了一个小障碍的努力得到它设置为允许抖动检测之间的抖动检测和时间的敏感性定制。

In my efforts to try to learn more about Android development and using user preferences I've created a little application that works fine and has a number of options that the user can change to make it look different. However, I've run into a little snag trying to get it setup to allow customization of the sensitivity of the shake detection and time between shake detection.

我所拥有的一切工作,所以,如果用户摇动手机就我想要做什么。下面是我所为抖动检测做了基础(基于在这里下车一个伟大的职位对计算器(的安卓:我想动摇它)):

I have everything working so that if a user shakes the phone it does what I want. Here are the basics of what I've done for the Shake Detection (based off of a great post here on stackoverflow(Android: I want to shake it)):

创建了一个名为ShakeDetector新类,把下面的code它:

Created a new class named ShakeDetector and put the following code in it:

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.FloatMath;

public class ShakeDetector implements SensorEventListener {

/*
 * The gForce that is necessary to register as shake.
 * Must be greater than 1G (one earth gravity unit).
 * You can install "G-Force", by Blake La Pierre
 * from the Google Play Store and run it to see how
 *  many G's it takes to register a shake
 */
private static final float SHAKE_THRESHOLD_GRAVITY = 2.7F;
private static final int SHAKE_SLOP_TIME_MS = 500;
private static final int SHAKE_COUNT_RESET_TIME_MS = 3000;

private OnShakeListener mListener;
private long mShakeTimestamp;
private int mShakeCount;

public void setOnShakeListener(OnShakeListener listener) {
    this.mListener = listener;
}

public interface OnShakeListener {
    public void onShake(int count);
}

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

@Override
public void onSensorChanged(SensorEvent event) {

    if (mListener != null) {
        float x = event.values[0];
        float y = event.values[1];
        float z = event.values[2];

        float gX = x / SensorManager.GRAVITY_EARTH;
        float gY = y / SensorManager.GRAVITY_EARTH;
        float gZ = z / SensorManager.GRAVITY_EARTH;

        // gForce will be close to 1 when there is no movement.
        float gForce = FloatMath.sqrt(gX * gX + gY * gY + gZ * gZ);

        if (gForce > SHAKE_THRESHOLD_GRAVITY) {
            final long now = System.currentTimeMillis();
            // ignore shake events too close to each other (500ms)
            if (mShakeTimestamp + SHAKE_SLOP_TIME_MS > now) {
                return;
            }

            // reset the shake count after 3 seconds of no shakes
            if (mShakeTimestamp + SHAKE_COUNT_RESET_TIME_MS < now) {
                mShakeCount = 0;
            }

            mShakeTimestamp = now;
            mShakeCount++;

            mListener.onShake(mShakeCount);
        }
    }
}
}

接下来,我把我的我的主要活动的onCreate方法如下:

Next I put the following in my onCreate method of my main activity:

        // ShakeDetector initialization
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mAccelerometer = mSensorManager
            .getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    mShakeDetector = new ShakeDetector();
    mShakeDetector.setOnShakeListener(new OnShakeListener() {

        @Override
        public void onShake(int count) {
            /*
             * The following method, "handleShakeEvent(count):" is a stub //
             * method you would use to setup whatever you want done once the
             * device has been shook.
             */
            handleShakeEvent(count);
        }
    });

此外,在这一点上根据需要一切正常。不过,我不知道该怎么办是建立SHAKE_THRESHOLD_GRAVITY和SHAKE_COUNT_RESET_TIME_MS在ShakeDetector类使用共享preferences我已经在应用程序安装。一切都在应用程序中配置(和作品),以允许用户进入并选择两个的这些设置不同的值,但我不知道如何从该活动通过共享preferences设置这一类。我已经尝试了一些不同的东西,没有运气,我似乎无法在网上找到任何东西,详细介绍了如何做到这一点。这也可能是一些相当简单,但我没有多少运气计算出来。

Again, at this point everything works as desired. However, what I'm not sure how to do is setup SHAKE_THRESHOLD_GRAVITY and SHAKE_COUNT_RESET_TIME_MS in the ShakeDetector class to use the shared preferences I already have setup in the application. Everything is configured in the application (and works) to allow the user to go in and select a different value for both of those settings, but I'm not sure how to pass the SharedPreferences settings from the activity to this class. I've tried a number of different things with no luck and I can't seem to find anything online that details how to do this. It's probably something rather simple, but I'm not having much luck figuring it out.

在概括地说,我一直在努力,创造了ShakeDetector类的另一种方法(例如setShake preferences()),然后把code它看起来类似于以下内容:

In a nutshell, I've tried to create another method in the ShakeDetector class (e.g. setShakePreferences()) and then put code in it that looks similar to the following:

    public void setShakePreferences() {

    shake_sensitivity = myPrefs.getString(SHAKE_THRESHOLD_GRAVITY2, "2.7");
    shake_time_between = myPrefs.getString(SHAKE_COUNT_RESET_TIME_MS2, "3000");
    float shake_threshold_gravity = Float.valueOf(shake_sensitivity);
    int shake_count_reset_time_ms = Integer.valueOf(shake_time_between);

}

我试图传递共享preferences(如setShake preferences(共享preferences我的preFS))各种不同的方式,但是,一切我试图做的就是我的preFS实际上包含共享preferences只有永远似乎与我的preFS空值结束。我有我的主要活动的一些设置,通过用户preferences控制和我有相似的是上面的工作就好方法。我只是不知道如何设置我的preFS实际的共享preferences值在ShakeDetector类。

I've tried passing in SharedPreferences (e.g. setShakePreferences(SharedPreferences myPrefs)) various different ways, however, everything I've tried to do to get myPrefs to actually contain the SharedPreferences only ever seems to end up with a null value for myPrefs. I have some settings in my main activity that are controlled through the user preferences and I have methods similar to what is above that work just fine. I'm just not sure how to set myPrefs to the actual SharedPreferences values in the ShakeDetector class.

请帮忙。解决方案的详细code例子将努力所能帮助我理解我怎么能做到这一点。谢谢!

Please help. Detailed code examples of solutions would work best to help me understand how I can accomplish this. Thanks!

推荐答案

阅读起来多了几分如何实现接口后想通这一个。它实际上是pretty简单,一旦我想通了(不知道为什么我没有赶上它开始与)。

Figured this one out after reading up a little more on how to implement interfaces. It was actually pretty simple once I figured it out (not sure why I didn't catch it to begin with).

基本上,我修改的onCreate()来传递共享preferences如下(只是增加了this.my preFS作为参数):

Basically, I modified onCreate() to pass the sharedPreferences as follows (just added "this.myPrefs" as a parameter):

        // ShakeDetector initialization
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    mShakeDetector = new ShakeDetector();
    mShakeDetector.setOnShakeListener(new OnShakeListener() {

        @Override
        public void onShake(int count) {
            /*
             * The following method, "handleShakeEvent(count):" is a stub //
             * method you would use to setup whatever you want done once the
             * device has been shook.
             */
            handleShakeEvent(count);
        }
    }, this.myPrefs); // <<<--- ADDED IT HERE

然后我不得不修改setOnShakeListener在ShakeDetector类接受我的preFS作为参数,并添加一切,所以它会正确处理的变量。这里是我结束了:

Then I had to modify the setOnShakeListener in the ShakeDetector class to accept myPrefs as a parameter and added everything so that it would correctly handle the variables. Here's what I ended up with:

import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.FloatMath;
import android.util.Log;

public class ShakeDetector implements SensorEventListener {

/*
 * The gForce that is necessary to register as shake.
 * Must be greater than 1G (one earth gravity unit).
 * You can install "G-Force", by Blake La Pierre
 * from the Google Play Store and run it to see how
 *  many G's it takes to register a shake
 */
private static final String SHAKE_THRESHOLD_GRAVITY = "<replace this with the android:key value you have configured in you preferences XML file.>";
private static final String SHAKE_COUNT_RESET_TIME_MS = "<replace this with the android:key value you have configured in you preferences XML file.>";
private static final String SHAKE_SLOP_TIME_MS = "<replace this with the android:key value you have configured in you preferences XML file.>";

private OnShakeListener mListener;
private long mShakeTimestamp;
private int mShakeCount;
private SharedPreferences myPrefs;

public void setOnShakeListener(OnShakeListener listener, SharedPreferences myPrefs) {
    this.mListener = listener;
    this.myPrefs = myPrefs;
}

public interface OnShakeListener {
    public void onShake(int count);
}

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

@Override
public void onSensorChanged(SensorEvent event) {

    if (mListener != null) {
        float x = event.values[0];
        float y = event.values[1];
        float z = event.values[2];

        float gX = x / SensorManager.GRAVITY_EARTH;
        float gY = y / SensorManager.GRAVITY_EARTH;
        float gZ = z / SensorManager.GRAVITY_EARTH;

        // gForce will be close to 1 when there is no movement.
        float gForce = FloatMath.sqrt(gX * gX + gY * gY + gZ * gZ);

        if (gForce > Float.parseFloat(myPrefs.getString(SHAKE_THRESHOLD_GRAVITY, "2.7F"))) {
            final long now = System.currentTimeMillis();
            // ignore shake events too close to each other (500ms)
            if (mShakeTimestamp + Integer.parseInt(myPrefs.getString(SHAKE_SLOP_TIME_MS, "500")) > now) {
                return;
            }

            // reset the shake count after 3 seconds of no shakes
            if (mShakeTimestamp + Integer.parseInt(myPrefs.getString(SHAKE_COUNT_RESET_TIME_MS, "3000")) < now) {
                mShakeCount = 0;
            }

            mShakeTimestamp = now;
            mShakeCount++;

            mListener.onShake(mShakeCount);
        }
    }
}
}

希望有所帮助,如果任何人想知道。

Hope that helps if anyone else was wondering.

这篇关于安卓:在摇监听器类使用共享preferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆