Android 微信搖一搖功能實現,最近學習感應器,就想實現搖一搖的功能,上網查了些資料,就整理下。如有錯誤,還請指正。
開發環境
- Android Studio 2.2.1
- JDK1.7
- API 24
- Gradle 2.2.1
相關知識點
- 加速度感應器
- 補間動畫
- 手機震動 (Vibrator)
- 較短 聲音/音效 的播放 (SoundPool)
案例:
我們接下來分析一下這個案例, 當使用者晃動手機時, 會觸發加速感應器, 此時加速感應器會調用相應介面供我們使用, 此時我們可以做一些相應的動畫效果, 震動效果和聲音效果. 大致思路就是這樣. 具體功能點:
使用者晃動後兩張圖片分開, 顯示後面圖片
晃動後伴隨震動效果, 聲音效果
根據以上的簡單分析, 我們就知道該怎麼做了, Just now
先搭建布局
布局沒啥可說的, 大家直接看代碼吧
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ff222222" android:orientation="vertical" tools:context="com.lulu.weichatshake.MainActivity"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <!--搖一搖中心圖片--> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:src="@mipmap/weichat_icon"/> <LinearLayout android:gravity="center" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true"> <!--頂部的橫線和圖片--> <LinearLayout android:gravity="center_horizontal|bottom" android:id="@+id/main_linear_top" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <ImageView android:src="@mipmap/shake_top" android:id="@+id/main_shake_top" android:layout_width="wrap_content" android:layout_height="100dp"/> <ImageView android:background="@mipmap/shake_top_line" android:id="@+id/main_shake_top_line" android:layout_width="match_parent" android:layout_height="5dp"/> </LinearLayout> <!--底部的橫線和圖片--> <LinearLayout android:gravity="center_horizontal|bottom" android:id="@+id/main_linear_bottom" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <ImageView android:background="@mipmap/shake_bottom_line" android:id="@+id/main_shake_bottom_line" android:layout_width="match_parent" android:layout_height="5dp"/> <ImageView android:src="@mipmap/shake_bottom" android:id="@+id/main_shake_bottom" android:layout_width="wrap_content" android:layout_height="100dp"/> </LinearLayout> </LinearLayout> </RelativeLayout></LinearLayout>
得到加速度感應器的回調介面
step1: 在onStart() 方法中擷取感應器的SensorManager
@Overrideprotected void onStart() { super.onStart(); //擷取 SensorManager 負責管理感應器 mSensorManager = ((SensorManager) getSystemService(SENSOR_SERVICE)); if (mSensorManager != null) { //擷取加速度感應器 mAccelerometerSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); if (mAccelerometerSensor != null) { mSensorManager.registerListener(this, mAccelerometerSensor, SensorManager.SENSOR_DELAY_UI); } }}
step2: 緊接著我們就要在Pause中登出感應器
@Overrideprotected void onPause() { // 務必要在pause中登出 mSensorManager // 否則會造成介面退出後搖一搖依舊生效的bug if (mSensorManager != null) { mSensorManager.unregisterListener(this); } super.onPause();}
Note: 至於為什麼我們要在onStart和onPause中就行SensorManager的註冊和登出, 就是因為, 防止在介面退出(包括按Home鍵)時, 搖一搖依舊生效(代碼中有注釋)
step3: 在step1中的註冊監聽事件方法中, 我們傳入了當前Activity對象, 故讓其實現回調介面, 得到以下方法
///////////////////////////////////////////////////////////////////////////// SensorEventListener回調方法///////////////////////////////////////////////////////////////////////////@Overridepublic void onSensorChanged(SensorEvent event) { int type = event.sensor.getType(); if (type == Sensor.TYPE_ACCELEROMETER) { //擷取三個方向值 float[] values = event.values; float x = values[0]; float y = values[1]; float z = values[2]; if ((Math.abs(x) > 17 || Math.abs(y) > 17 || Math .abs(z) > 17) && !isShake) { isShake = true; // TODO: 2016/10/19 實現搖動邏輯, 搖動後進行震動 Thread thread = new Thread() { @Override public void run() { super.run(); try { Log.d(TAG, "onSensorChanged: 搖動"); //開始震動 發出提示音 展示動畫效果 mHandler.obtainMessage(START_SHAKE).sendToTarget(); Thread.sleep(500); //再來一次震動提示 mHandler.obtainMessage(AGAIN_SHAKE).sendToTarget(); Thread.sleep(500); mHandler.obtainMessage(END_SHAKE).sendToTarget(); } catch (InterruptedException e) { e.printStackTrace(); } } }; thread.start(); } }}@Overridepublic void onAccuracyChanged(Sensor sensor, int accuracy) {}
Note: 當使用者晃動手機會調用onSensorChanged方法, 可以做一些相應的操作
為解決動畫和震動延遲, 我們開啟了一個子線程來實現.
子線程中會通過發送Handler訊息, 先開始動畫效果, 並伴隨震動和聲音 ,先把Handler的實現放一放, 我們再來看一下震動和聲音初始化動畫, 震動和音效實現
step 1: 先擷取到震動相關的服務,注意要加許可權. 至於音效, 我們採用SoundPool來播放, 在這裡非常感謝Vincent 的貼子, 好初始化SoundPool
震動許可權
<uses-permission android:name="android.permission.VIBRATE"/>
//初始化SoundPoolmSoundPool = new SoundPool(1, AudioManager.STREAM_SYSTEM, 5);mWeiChatAudio = mSoundPool.load(this, R.raw.weichat_audio, 1);//擷取Vibrator震動服務mVibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
Note: 大家可能發現SoundPool的構造方法已經過時, 不過不用擔心這是Api21之後過時的, 所以也不算太”過時”吧
step2: 接下來我們就要介紹Handler中的實現了, 為避免Activity記憶體流失, 採用了軟引用方式
private static class MyHandler extends Handler { private WeakReference<MainActivity> mReference; private MainActivity mActivity; public MyHandler(MainActivity activity) { mReference = new WeakReference<MainActivity>(activity); if (mReference != null) { mActivity = mReference.get(); } } @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case START_SHAKE: //This method requires the caller to hold the permission VIBRATE. mActivity.mVibrator.vibrate(300); //發出提示音 mActivity.mSoundPool.play(mActivity.mWeiChatAudio, 1, 1, 0, 0, 1); mActivity.mTopLine.setVisibility(View.VISIBLE); mActivity.mBottomLine.setVisibility(View.VISIBLE); mActivity.startAnimation(false);//參數含義: (不是回來) 也就是說兩張圖片分散開的動畫 break; case AGAIN_SHAKE: mActivity.mVibrator.vibrate(300); break; case END_SHAKE: //整體效果結束, 將震動設定為false mActivity.isShake = false; // 展示上下兩種圖片回來的效果 mActivity.startAnimation(true); break; } }}
Note: 內容不多說了, 代碼注釋中很詳細, 還有一個startAnimation方法
我先來說一下它的參數, true表示布局中兩張圖片從開啟到關閉的動畫, 反之, false是從關閉到開啟狀態, 上代碼
step3: startAnimaion方法上的實現
/** * 開啟 搖一搖動畫 * * @param isBack 是否是返回初識狀態 */private void startAnimation(boolean isBack) { //動畫座標移動的位置的類型是相對自己的 int type = Animation.RELATIVE_TO_SELF; float topFromY; float topToY; float bottomFromY; float bottomToY; if (isBack) { topFromY = -0.5f; topToY = 0; bottomFromY = 0.5f; bottomToY = 0; } else { topFromY = 0; topToY = -0.5f; bottomFromY = 0; bottomToY = 0.5f; } //上面圖片的動畫效果 TranslateAnimation topAnim = new TranslateAnimation( type, 0, type, 0, type, topFromY, type, topToY ); topAnim.setDuration(200); //動畫終止時停留在最後一幀~不然會回到沒有執行之前的狀態 topAnim.setFillAfter(true); //底部的動畫效果 TranslateAnimation bottomAnim = new TranslateAnimation( type, 0, type, 0, type, bottomFromY, type, bottomToY ); bottomAnim.setDuration(200); bottomAnim.setFillAfter(true); //大家一定不要忘記, 當要回來時, 我們中間的兩根線需要GONE掉 if (isBack) { bottomAnim.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) {} @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationEnd(Animation animation) { //當動畫結束後 , 將中間兩條線GONE掉, 不讓其佔位 mTopLine.setVisibility(View.GONE); mBottomLine.setVisibility(View.GONE); } }); } //設定動畫 mTopLayout.startAnimation(topAnim); mBottomLayout.startAnimation(bottomAnim);}
至此 核心代碼已經介紹完畢 , 但是還有部分小細節不得不提一下
細枝末節
大家要在初始化View之前將上下兩條橫線GONE掉, 用GONE是不佔位的
mTopLine.setVisibility(View.GONE);
mBottomLine.setVisibility(View.GONE);
2.咱們的搖一搖最好是只豎屏 (畢竟我也沒見過橫屏的搖一搖), 加上下面代碼
//設定只豎屏
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
完整代碼
源碼我已經發在了github上, 希望大家多多支援!
感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!