传感器使用-指南针

package com.pas.classic.compass;

import com.pas.compass.R;

import cn.waps.AdInfo;
import cn.waps.AppConnect;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.provider.ContactsContract.AggregationExceptions;
import android.app.Activity;
import android.view.Menu;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.AdapterViewFlipper;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    private SensorManager sm;
    private ImageView iv_compass;
    MyListener listener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	sm = (SensorManager) getSystemService(SENSOR_SERVICE);
	iv_compass = (ImageView) findViewById(R.id.iv_compass); 
	
	// 得到方向传感器
	Sensor sensor = sm.getDefaultSensor(Sensor.TYPE_ORIENTATION);
	if (sensor == null) {
	    Toast.makeText(this, "您的手机没有方向感应器,即将退出", Toast.LENGTH_LONG).show();
	    finish();
	    return;
	}
	listener = new MyListener();
	sm.registerListener(listener, sensor,
		SensorManager.SENSOR_DELAY_FASTEST);

    }

    private class MyListener implements SensorEventListener {

	float startangle = 0f;

	/**
	 * 传感器数据变化执行
	 */
	@Override
	public void onSensorChanged(SensorEvent event) {
	    /**
	     * 方向传感器时 此值代表与正北的角度
	     */
	    float angle = Math.round(event.values[0]);
	    rotate(angle);
	    startangle = -angle;
	}

	private void rotate(float angle) {
	    RotateAnimation animation = new RotateAnimation(startangle, angle,
		    Animation.RELATIVE_TO_SELF, 0.5f,
		    Animation.RELATIVE_TO_SELF, 0.5f);
	    animation.setDuration(3000);
	    animation.setFillAfter(true);
	    iv_compass.startAnimation(animation);
	}

	/**
	 * 精确度发生变化 比如进入强磁场区收到干扰
	 */
	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
	    // TODO Auto-generated method stub

	}

    }

    @Override
    protected void onDestroy() {
	sm.unregisterListener(listener);
	super.onDestroy();
    }
}



你可能感兴趣的:(传感器使用-指南针)