android 類似微信的搖一搖功能實現思路及代碼

來源:互聯網
上載者:User

複製代碼 代碼如下:package com.eboy.testyaoyiyao;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity implements SensorEventListener {
//Sensor管理器
private SensorManager mSensorManager = null;
//震動
private Vibrator mVibrator = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mVibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
public void onSensorChanged(SensorEvent arg0) {
// TODO Auto-generated method stub
int sensorType = arg0.sensor.getType();
float[] values = arg0.values;
if (sensorType == Sensor.TYPE_ACCELEROMETER){
if (Math.abs(values[0]) > 14 || Math.abs(values[1]) > 14 || Math.abs(values[2]) > 14){
mVibrator.vibrate(100);
TextView tv1 = (TextView)findViewById(R.id.textView1);
SimpleDateFormat f=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");
tv1.setText(f.format(new Date()) + "手機搖動了...");
}
}
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
mSensorManager.unregisterListener(this);
super.onStop();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
mSensorManager.unregisterListener(this);
super.onPause();
}
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.