国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統(tǒng) > Android > 正文

Android 微信搖一搖功能實(shí)現(xiàn)詳細(xì)介紹

2019-12-12 04:50:13
字體:
供稿:網(wǎng)友

Android 微信搖一搖功能實(shí)現(xiàn),最近學(xué)習(xí)傳感器,就想實(shí)現(xiàn)搖一搖的功能,上網(wǎng)查了些資料,就整理下。如有錯(cuò)誤,還請指正。

開發(fā)環(huán)境

  1. Android Studio 2.2.1
  2. JDK1.7
  3. API 24
  4. Gradle 2.2.1

相關(guān)知識(shí)點(diǎn)

  1. 加速度傳感器
  2. 補(bǔ)間動(dòng)畫
  3. 手機(jī)震動(dòng) (Vibrator)
  4. 較短 聲音/音效 的播放 (SoundPool)

案例:

我們接下來分析一下這個(gè)案例, 當(dāng)用戶晃動(dòng)手機(jī)時(shí), 會(huì)觸發(fā)加速傳感器, 此時(shí)加速傳感器會(huì)調(diào)用相應(yīng)接口供我們使用, 此時(shí)我們可以做一些相應(yīng)的動(dòng)畫效果, 震動(dòng)效果和聲音效果. 大致思路就是這樣. 具體功能點(diǎn):

用戶晃動(dòng)后兩張圖片分開, 顯示后面圖片
晃動(dòng)后伴隨震動(dòng)效果, 聲音效果

根據(jù)以上的簡單分析, 我們就知道該怎么做了, 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>

得到加速度傳感器的回調(diào)接口

step1: 在onStart() 方法中獲取傳感器的SensorManager

@Overrideprotected void onStart() {  super.onStart();  //獲取 SensorManager 負(fù)責(zé)管理傳感器  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() {  // 務(wù)必要在pause中注銷 mSensorManager  // 否則會(huì)造成界面退出后搖一搖依舊生效的bug  if (mSensorManager != null) {    mSensorManager.unregisterListener(this);  }  super.onPause();}

Note: 至于為什么我們要在onStart和onPause中就行SensorManager的注冊和注銷, 就是因?yàn)? 防止在界面退出(包括按Home鍵)時(shí), 搖一搖依舊生效(代碼中有注釋)

step3: 在step1中的注冊監(jiān)聽事件方法中, 我們傳入了當(dāng)前Activity對象, 故讓其實(shí)現(xiàn)回調(diào)接口, 得到以下方法

///////////////////////////////////////////////////////////////////////////// SensorEventListener回調(diào)方法///////////////////////////////////////////////////////////////////////////@Overridepublic void onSensorChanged(SensorEvent event) {  int type = event.sensor.getType();  if (type == Sensor.TYPE_ACCELEROMETER) {    //獲取三個(gè)方向值    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 實(shí)現(xiàn)搖動(dòng)邏輯, 搖動(dòng)后進(jìn)行震動(dòng)      Thread thread = new Thread() {        @Override        public void run() {          super.run();          try {            Log.d(TAG, "onSensorChanged: 搖動(dòng)");            //開始震動(dòng) 發(fā)出提示音 展示動(dòng)畫效果            mHandler.obtainMessage(START_SHAKE).sendToTarget();            Thread.sleep(500);            //再來一次震動(dòng)提示            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: 當(dāng)用戶晃動(dòng)手機(jī)會(huì)調(diào)用onSensorChanged方法, 可以做一些相應(yīng)的操作

為解決動(dòng)畫和震動(dòng)延遲, 我們開啟了一個(gè)子線程來實(shí)現(xiàn).

子線程中會(huì)通過發(fā)送Handler消息, 先開始動(dòng)畫效果, 并伴隨震動(dòng)和聲音 ,先把Handler的實(shí)現(xiàn)放一放, 我們再來看一下震動(dòng)和聲音初始化動(dòng)畫, 震動(dòng)和音效實(shí)現(xiàn)

step 1: 先獲取到震動(dòng)相關(guān)的服務(wù),注意要加權(quán)限. 至于音效, 我們采用SoundPool來播放, 在這里非常感謝Vincent 的貼子, 好初始化SoundPool

震動(dòng)權(quán)限

    <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震動(dòng)服務(wù)mVibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);

Note: 大家可能發(fā)現(xiàn)SoundPool的構(gòu)造方法已經(jīng)過時(shí), 不過不用擔(dān)心這是Api21之后過時(shí)的, 所以也不算太”過時(shí)”吧  

step2: 接下來我們就要介紹Handler中的實(shí)現(xiàn)了, 為避免Activity內(nèi)存泄漏, 采用了軟引用方式

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);        //發(fā)出提示音        mActivity.mSoundPool.play(mActivity.mWeiChatAudio, 1, 1, 0, 0, 1);        mActivity.mTopLine.setVisibility(View.VISIBLE);        mActivity.mBottomLine.setVisibility(View.VISIBLE);        mActivity.startAnimation(false);//參數(shù)含義: (不是回來) 也就是說兩張圖片分散開的動(dòng)畫        break;      case AGAIN_SHAKE:        mActivity.mVibrator.vibrate(300);        break;      case END_SHAKE:        //整體效果結(jié)束, 將震動(dòng)設(shè)置為false        mActivity.isShake = false;        // 展示上下兩種圖片回來的效果        mActivity.startAnimation(true);        break;    }  }}

Note: 內(nèi)容不多說了, 代碼注釋中很詳細(xì), 還有一個(gè)startAnimation方法
我先來說一下它的參數(shù), true表示布局中兩張圖片從打開到關(guān)閉的動(dòng)畫, 反之, false是從關(guān)閉到打開狀態(tài), 上代碼

step3: startAnimaion方法上的實(shí)現(xiàn)

/** * 開啟 搖一搖動(dòng)畫 * * @param isBack 是否是返回初識(shí)狀態(tài) */private void startAnimation(boolean isBack) {  //動(dòng)畫坐標(biāo)移動(dòng)的位置的類型是相對自己的  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;  }  //上面圖片的動(dòng)畫效果  TranslateAnimation topAnim = new TranslateAnimation(      type, 0, type, 0, type, topFromY, type, topToY  );  topAnim.setDuration(200);  //動(dòng)畫終止時(shí)停留在最后一幀~不然會(huì)回到?jīng)]有執(zhí)行之前的狀態(tài)  topAnim.setFillAfter(true);  //底部的動(dòng)畫效果  TranslateAnimation bottomAnim = new TranslateAnimation(      type, 0, type, 0, type, bottomFromY, type, bottomToY  );  bottomAnim.setDuration(200);  bottomAnim.setFillAfter(true);  //大家一定不要忘記, 當(dāng)要回來時(shí), 我們中間的兩根線需要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) {        //當(dāng)動(dòng)畫結(jié)束后 , 將中間兩條線GONE掉, 不讓其占位        mTopLine.setVisibility(View.GONE);        mBottomLine.setVisibility(View.GONE);      }    });  }  //設(shè)置動(dòng)畫  mTopLayout.startAnimation(topAnim);  mBottomLayout.startAnimation(bottomAnim);}

至此 核心代碼已經(jīng)介紹完畢 , 但是還有部分小細(xì)節(jié)不得不提一下

細(xì)枝末節(jié)

大家要在初始化View之前將上下兩條橫線GONE掉, 用GONE是不占位的

mTopLine.setVisibility(View.GONE);
mBottomLine.setVisibility(View.GONE);

2.咱們的搖一搖最好是只豎屏 (畢竟我也沒見過橫屏的搖一搖), 加上下面代碼

//設(shè)置只豎屏
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

完整代碼

源碼我已經(jīng)發(fā)在了github上, 希望大家多多支持!

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 玉山县| 铜陵市| 珠海市| 宜阳县| 淳化县| 额尔古纳市| 江孜县| 西峡县| 东台市| 镇巴县| 汤原县| 北安市| 海安县| 星子县| 南城县| 景德镇市| 长阳| 普兰县| 金阳县| 民权县| 农安县| 秦皇岛市| 乐亭县| 旬邑县| 塔城市| 黄山市| 阳西县| 班玛县| 邯郸县| 龙南县| 孝感市| 游戏| 外汇| 惠水县| 宾川县| 长葛市| 湘潭市| 扎兰屯市| 南投县| 沭阳县| 康定县|