android shake that thing

    Today we talk about shaking, taking shaking the phone to switch wallpapers as an example.

    First of all, let’s talk about the shaking. Those who make mobile phones should know that this shaking is gravity sensing, that is, Gsensor.

	public void startListener(){
		try{
			if(mSensorManager == null){
				mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
			}
		}catch(Exception e){
			Log.d("dream.zhou","SensorManager not exist");
		}
		
		if((null != mSensorManager) && (mSensor == null)){
			mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		}
		if(null != mSensor){
			mSensorManager.registerListener(ShakeBackListener.this,mSensor,SensorManager.SENSOR_DELAY_GAME,null);
		}
	}

First we get the SensorManager, which, as the name implies, is the Manager that manages the Sensor sensor; then we get the Sensor sensor code-named Sensor.TYPE_ACCELEROMETER; finally we register our Sensor with the SensorManager. In this way, we have Gsensor, so where is our sensing place?
	@Override
	public void onSensorChanged(SensorEvent event) {
		// TODO Auto-generated method stub
		long currentUpdateTime = System.currentTimeMillis();
		long timeInterval = currentUpdateTime - mLastUpdateTime;
				
		if(timeInterval < SHAKE_TIME)return;
		mLastUpdateTime = currentUpdateTime;
		
		float x = event.values[0];
		float y = event.values[1];
		float z = event.values[2];
		
		float deltaX = x - mLastX;
		float deltaY = y - mLastY;
		float deltaZ = z - mLastZ;
		
		mLastX = x;
		mLastY = y;
		mLastZ = z;
		
		double speed = ((Math.sqrt(deltaX*deltaX + deltaY*deltaY + deltaZ*deltaZ))/timeInterval)*10000;

		if((speed >= SHAKE_SPEED)&&((mLastUpdateTime - mLastChangeWallpaperTime) >= CHANGE_WALLPAPER_TIME)){
			mLastChangeWallpaperTime = mLastUpdateTime;
			mOnShakeListener.onShake();
		}

	}

That’s it. First, we receive data every once in a while, which is our x, y, and z here. Through the difference with the last mLastX, mLastY, mLastZ, we calculate the shaking speed, and finally we judge that the speed is greater than a certain value. A value to do what we want to do. What's the deal with this? For example, if we want to talk about switching wallpapers, switching music, finding friends, answering calls, shaking, etc. Anyway, there are too many of them, these are all manifestations, but the essence is the same of. Our mOnShakeListener.onShake(); here is an interface.

Then let's talk about switching wallpapers
	@Override
	public void onCreate(){
		mContext = this;
		findWallpapers();
		mShakeBackListener = new ShakeBackListener(ShakeBackService.this);
		mOnShakeListener = new OnShakeListener(){
			@Override
			public void onShake(){
				// TODO Auto-generated method stub	
				nextWallpaper = Settings.System.getInt(mContext.getContentResolver(),"launcher.current.wallpaper",0) + 1;
				if(nextWallpaper >= mWallpaperCount){
					nextWallpaper = 0;
				}
				vibrate(VIBRATOR_TIME,needVibrate);
				selectWallpaper(nextWallpaper);
				Settings.System.putInt(mContext.getContentResolver(),"launcher.current.wallpaper",nextWallpaper);
			}
		};
		
		mShakeBackListener.setOnShakeListener(mOnShakeListener);
		mShakeBackListener.startListener();
		super.onCreate();
	}

This is the onShake() interface we mentioned just now. First, we will get the number of the system wallpaper the current wallpaper is, and then get the number of nextWallpaper, and then judge if it is the last one, then transfer to the first. One, and then we let the mobile phone vibrate, so that our users will feel very good, knowing that the shaking is OK, the wallpaper has been switched, and then the wallpaper is switched selectWallpaper(nextWallpaper);
    private void selectWallpaper(int position) {
        try {
            WallpaperManager wpm = (WallpaperManager) this.getSystemService(
                    Context.WALLPAPER_SERVICE);
            wpm.setResource(mImages.get(position));
        } catch (IOException e) {
            Log.e("dream.zhou", "Failed to set wallpaper: " + e);
        }
    }

Get the WallpaperManager, which is the wallpaper manager, and then get the ID of the wallpaper we need: mImages.get(position), and finally wpm.setResource(mImages.get(position)); replace the wallpaper. After we switch the wallpaper, we will record which one the current wallpaper is. In fact, I know that everyone can understand these things, so I won’t talk too much, and post the complete code for everyone’s reference.


The first is our Sensor class:

package com.android.launcher2.shake;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;


public class ShakeBackListener implements SensorEventListener {
	
	private static final int SHAKE_SPEED = 1000;
	private static final int SHAKE_TIME = 200;
	private static final int CHANGE_WALLPAPER_TIME = 1500;
	private SensorManager mSensorManager = null;
	private Sensor mSensor = null;
	private OnShakeListener mOnShakeListener = null;
	private Context mContext = null;
	private float mLastX = 0;
	private float mLastY = 0;
	private float mLastZ = 0;
	private long mLastUpdateTime = 0;
	private long mLastChangeWallpaperTime = 2000;
		
	public ShakeBackListener(Context c){		
		mContext = c;
	}
	
	public void startListener(){
		try{
			if(mSensorManager == null){
				mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
			}
		}catch(Exception e){
			Log.d("dream.zhou","SensorManager not exist");
		}
		
		if((null != mSensorManager) && (mSensor == null)){
			mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		}
		if(null != mSensor){
			mSensorManager.registerListener(ShakeBackListener.this,mSensor,SensorManager.SENSOR_DELAY_GAME,null);
		}
	}
	
	public void stopListener(){		
		if(null != mSensorManager){
			mSensorManager.unregisterListener(this);
		}
	}
	
	public interface OnShakeListener{
		public void onShake();
	}
	
	public void setOnShakeListener(OnShakeListener listener){
		mOnShakeListener = listener;
	}

	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		// TODO Auto-generated method stub
		long currentUpdateTime = System.currentTimeMillis();
		long timeInterval = currentUpdateTime - mLastUpdateTime;
				
		if(timeInterval < SHAKE_TIME)return;
		mLastUpdateTime = currentUpdateTime;
		
		float x = event.values[0];
		float y = event.values[1];
		float z = event.values[2];
		
		float deltaX = x - mLastX;
		float deltaY = y - mLastY;
		float deltaZ = z - mLastZ;
		
		mLastX = x;
		mLastY = y;
		mLastZ = z;
		
		double speed = ((Math.sqrt(deltaX*deltaX + deltaY*deltaY + deltaZ*deltaZ))/timeInterval)*10000;

		if((speed >= SHAKE_SPEED)&&((mLastUpdateTime - mLastChangeWallpaperTime) >= CHANGE_WALLPAPER_TIME)){
			mLastChangeWallpaperTime = mLastUpdateTime;
			mOnShakeListener.onShake();
		}

	}

}

下面是我的Service类了:

package com.android.launcher2.shake;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.Vibrator;
import com.android.launcher2.shake.ShakeBackListener.OnShakeListener;
import android.util.Log;
import android.app.WallpaperManager;
import java.io.IOException;
import com.android.launcher.R;
import android.content.res.Resources;
import java.util.ArrayList;
import android.provider.Settings;

public class ShakeBackService extends Service{
	
	private long VIBRATOR_TIME = 50;
	private ShakeBackListener mShakeBackListener = null;
	private OnShakeListener mOnShakeListener = null;
	private Vibrator mVibrator = null;
	private Context mContext = null;
	private boolean needVibrate = true;
	private ArrayList<Integer> mImages;
	private int nextWallpaper = 0;
	private int mWallpaperCount = 0;
	
	private IShakeBackService.Stub mBinder = new IShakeBackService.Stub() {
		
	};
	
	@Override
	public void onCreate(){
		mContext = this;
		findWallpapers();
		mShakeBackListener = new ShakeBackListener(ShakeBackService.this);
		mOnShakeListener = new OnShakeListener(){
			@Override
			public void onShake(){
				// TODO Auto-generated method stub	
				Log.d("dream.zhou.launcher2222","mWallpaperCount="+mWallpaperCount);
				nextWallpaper = Settings.System.getInt(mContext.getContentResolver(),"launcher.current.wallpaper",0) + 1;
				Log.d("dream.zhou.launcher2222","nextWallpaper="+nextWallpaper);
				if(nextWallpaper >= mWallpaperCount){
					nextWallpaper = 0;
				}
				vibrate(VIBRATOR_TIME,needVibrate);
				selectWallpaper(nextWallpaper);
				Settings.System.putInt(mContext.getContentResolver(),"launcher.current.wallpaper",nextWallpaper);
			}
		};
		
		mShakeBackListener.setOnShakeListener(mOnShakeListener);
		mShakeBackListener.startListener();
		super.onCreate();
	}

    private void findWallpapers() {
        mImages = new ArrayList<Integer>(24);

		mWallpaperCount = 0;

        final Resources resources = getResources();
        final String packageName = resources.getResourcePackageName(R.array.wallpapers);

        addWallpapers(resources, packageName, R.array.wallpapers);
        addWallpapers(resources, packageName, R.array.extra_wallpapers);
    }

    private void addWallpapers(Resources resources, String packageName, int list) {
        final String[] extras = resources.getStringArray(list);
        for (String extra : extras) {
            int res = resources.getIdentifier(extra, "drawable", packageName);
            if (res != 0) {
				mWallpaperCount++;
                mImages.add(res);
            }
        }
    }

    private void selectWallpaper(int position) {
        try {
            WallpaperManager wpm = (WallpaperManager) this.getSystemService(
                    Context.WALLPAPER_SERVICE);
            wpm.setResource(mImages.get(position));
        } catch (IOException e) {
            Log.e("dream.zhou", "Failed to set wallpaper: " + e);
        }
    }

	private void vibrate(long duration,boolean need){
		if(mVibrator == null){
			mVibrator = (Vibrator)mContext.getSystemService(Context.VIBRATOR_SERVICE);
		}
		if(need){
			mVibrator.vibrate(duration);
		}
	}
		
	@Override
	public void onDestroy(){
		mShakeBackListener.stopListener();
		super.onDestroy();
	}

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

今天就说到这里,还是那句话给大师饭后取乐,给后来者抛砖引玉,别在背后骂我就行。




Guess you like

Origin blog.csdn.net/zhiyuan263287/article/details/18656187