Android----机选摇一摇,猜大小功能

今天继续为朋友们分享一个不一样的功能。

本篇讲的是摇一摇,猜大小,晃动手机,唤起震动,两个按钮自动切换,停止时,随机停在某一个按钮上。

Android----机选摇一摇,猜大小功能_第1张图片

样式上丑了点。不过功能最主要了。

import android.annotation.SuppressLint;
import android.app.Service;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.CountDownTimer;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;

public class MainActivity extends AppCompatActivity implements SensorEventListener {
    TextView tv_bs;
    RelativeLayout rl_big, rl_small;
    TextView big, tv_big;
    TextView small, tv_small;
    ImageView select1,select2;
    private MyCountDownTimer mc;
    private Boolean canstart = true;
    private  int j=0;
    private  int i=0;
    private Vibrator vibrator;
    private SensorManager mSensorManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.header_new_solobigsmall);
        initView();
    }

    private void initView() {
        mc = new MyCountDownTimer(1000, 200);
        tv_bs = findViewById(R.id.tv_bs);
        rl_big =  findViewById(R.id.rl_big);
        rl_small =  findViewById(R.id.rl_small);
        small =  findViewById(R.id.small);
        tv_small =  findViewById(R.id.tv_small);
        big =  findViewById(R.id.big);
        tv_big = findViewById(R.id.tv_big);
        select1=findViewById(R.id.select1);
        select2=findViewById(R.id.select2);
        // 获取传感器管理服务
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        // 震动
        vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
        rl_big.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setBigSmall(1);
            }
        });
        rl_small.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setBigSmall(2);
            }
        });
    }

    private void setBigSmall(int c){
        switch (c) {
            case 1:
                rl_small.setBackgroundResource(R.drawable.bd_solonotselect);
                small.setTextColor(getResources().getColor(R.color.cs_999999));
                tv_small.setTextColor(getResources().getColor(R.color.cs_999999));
                select2.setVisibility(View.GONE);
                big.setTextColor(getResources().getColor(R.color.red_packet));
                tv_big.setTextColor(getResources().getColor(R.color.red_packet));
                select1.setVisibility(View.VISIBLE);
                break;
            case 2:
                rl_big.setBackgroundResource(R.drawable.bd_solonotselect);
                big.setTextColor(getResources().getColor(R.color.cs_999999));
                tv_big.setTextColor(getResources().getColor(R.color.cs_999999));
                select1.setVisibility(View.GONE);
                rl_small.setBackgroundResource(R.drawable.bd_soloselect);
                small.setTextColor(getResources().getColor(R.color.red_packet));
                tv_small.setTextColor(getResources().getColor(R.color.red_packet));
                select2.setVisibility(View.VISIBLE);
                break;
            case 3:
                rl_big.setBackgroundResource(R.drawable.bd_solonotselect);
                big.setTextColor(getResources().getColor(R.color.cs_999999));
                tv_big.setTextColor(getResources().getColor(R.color.cs_999999));
                select1.setVisibility(View.GONE);
                rl_small.setBackgroundResource(R.drawable.bd_solonotselect);
                small.setTextColor(getResources().getColor(R.color.cs_999999));
                tv_small.setTextColor(getResources().getColor(R.color.cs_999999));
                select2.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    @SuppressLint("MissingPermission")
    @Override
    public void onSensorChanged(SensorEvent event) {
        int sensorType = event.sensor.getType();
        // values[0]:X轴,values[1]:Y轴,values[2]:Z轴
        float[] values = event.values;
        if (sensorType == Sensor.TYPE_ACCELEROMETER) {
            float x = values[0];
            float y = values[1];
            float z = values[2];
            int value = 19;
            // 摇一摇阀值,不同手机能达到的最大值不同,如某品牌手机只能达到20
            if (x >= value || x <= -value || y >= value || y <= -value || z >= value || z <= -value) {
                if (canstart) {
                    setBigSmall(3);
                    i = new Random().nextInt(2) + 1;
                    mc.start();
                    vibrator.vibrate(500);
                }
            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    class MyCountDownTimer extends CountDownTimer {
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            setBigSmall(j);
            canstart = true;

        }

        @Override
        public void onTick(long millisUntilFinished) {
            canstart = false;
            if (i == 1) {
                setBigSmall(3);
                setBigSmall(1);
                j = i;
                i = 2;
            } else if (i == 2) {
                setBigSmall(3);
                setBigSmall(2);
                j = i;
                i = 1;
            }
        }
    }

    @Override
    protected void onPause() {
        if (mSensorManager != null) {
            mSensorManager.unregisterListener(this);
        }
        Toast.makeText(MainActivity.this,"这传感解绑了",Toast.LENGTH_SHORT).show();
        super.onPause();
    }

    @Override
    protected void onStop() {
        if (mSensorManager != null) {
            mSensorManager.unregisterListener(this);
        }
        super.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 加速度传感器
        if (mSensorManager != null) {
            mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                    SensorManager.SENSOR_DELAY_NORMAL);
            Toast.makeText(MainActivity.this,"这初始化请求了",Toast.LENGTH_SHORT).show();
        }
    }
}

命名上没按驼峰那么规范,写的比较随性,写着玩的。就写个大概意思。

Android----机选摇一摇,猜大小功能_第2张图片

一顿乱扔,没分包,也没分drawable,写的过于随意了,谅解。就是想保证功能而已。

package com.example.administrator.yyy;

import android.os.CountDownTimer;

public class CountDownTimerUtils extends CountDownTimer {
   
    public interface CountDownTimerUtilsListener {
        void onTick(long millisUntilFinished);
        void onFinish();
    }
    
    public CountDownTimerUtilsListener countDownTimerUtilsListener;
    
   /**
    * 
    * @param millisInFuture
    *            表示以毫秒为单位 倒计时的总数
    * 
    *            例如 millisInFuture=1000 表示1秒
    * 
    * @param countDownInterval
    *            表示 间隔 多少微秒 调用一次 onTick 方法
    * 
    *            例如: countDownInterval =1000 ; 表示每1000毫秒调用一次onTick()
    * 
    */
   public CountDownTimerUtils(long millisInFuture, long countDownInterval, CountDownTimerUtilsListener countDownTimerUtilsListener) {
      super(millisInFuture, countDownInterval);
      this.countDownTimerUtilsListener = countDownTimerUtilsListener;
   }

   @Override
   public void onFinish() {
      countDownTimerUtilsListener.onFinish();
   }

   @Override
   public void onTick(long millisUntilFinished) {
      countDownTimerUtilsListener.onTick(millisUntilFinished);
   }
}

 

 

 

package com.example.administrator.yyy;

import org.json.JSONObject;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class DateUtils {
   
   /**
    * 取得毫秒与当前日期 差值
   * 

Title: getMillisecond

* @author cw * @date 2016年7月25日 下午4:15:06 * @return long *

Description:

* @param createTime * @return * */ public static long getMillisecondDifference(long createTime){ long currentMillisecond = System.currentTimeMillis(); if(currentMillisecondTitle: getCurrentMillis

* @author cw * @date 2016年8月22日 下午3:37:59 * @return long *

Description:

* @return * */ public static long getCurrentMillis(long createTime){ DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Calendar cMax = Calendar.getInstance(); cMax.setTimeInMillis(createTime * 1000L); String strMax = sdf.format(cMax.getTime()); try { Date dMax = sdf.parse(strMax); return dMax.getTime(); } catch (ParseException e) { e.printStackTrace(); } return 0; } /** * 计算指定时间到现在相隔天数 *

* Title: parseDate *

* * @author cw * @date 2016年6月25日 下午3:03:18 * @return long *

* Description: *

* @param createTime * @return * */ public static long parseOldToCurrent(long createTime) { try { DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Calendar cMax = Calendar.getInstance(); cMax.setTimeInMillis(createTime * 1000); Calendar cMin = Calendar.getInstance(); String strMax = sdf.format(cMax.getTime()); Date dMax = sdf.parse(strMax); String strMin = sdf.format(cMin.getTime()); Date dMin = sdf.parse(strMin); return (dMin.getTime() - dMax.getTime()) / (1000 * 60 * 60 * 24); } catch (ParseException e) { e.printStackTrace(); } return 0; } /** * 计算现在到指定时间相隔天数 *

* Title: parseDateDay *

* * @author cw * @date 2016年6月25日 下午2:39:33 * @return long *

* Description: *

* @param createTime * @return * */ private static long parseCurrentToFuture(long createTime) { try { DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Calendar cMax = Calendar.getInstance(); cMax.setTimeInMillis(createTime * 1000); Calendar cMin = Calendar.getInstance(); String strMax = sdf.format(cMax.getTime()); Date dMax = sdf.parse(strMax); String strMin = sdf.format(cMin.getTime()); Date dMin = sdf.parse(strMin); return (dMax.getTime() - dMin.getTime()) / (1000 * 60 * 60 * 24); } catch (ParseException e) { e.printStackTrace(); } return 0; } /** * 红包方案有效期 *

* Title: usablerdRedTime *

* * @author cw * @date 2016年6月25日 下午3:04:38 * @return String *

* Description: *

* @param createTime * @return * */ public static String usablerdRedTime(long createTime) { long lDay = parseCurrentToFuture(createTime) + 1; if (lDay == 1) { return "今天"; } else if (lDay < 301) { return lDay + "天"; } else if (lDay > 300 && lDay < (10 * 365 + 1)) { return toDateSimplay(createTime); } else if (lDay > 10 * 365) { return "永久有效"; }else { return ""; } } /** * 我的晒单列表日期 *

* Title: getDateShowOff *

* * @author cw * @date 2016年5月27日 下午5:18:41 * @return String *

* Description: *

* @param t * @return * */ public static String getDateShowOff(long t) { Calendar c = Calendar.getInstance(); c.setTimeInMillis(t * 1000); long iDay = parseOldToCurrent(t); if (iDay == 0) { return "今天"; } else if (iDay == 1) { return "昨天"; } else { DateFormat sdf = new SimpleDateFormat("dd"); String iDay1 = sdf.format(c.getTime()); sdf = new SimpleDateFormat("M月"); String iMonth = sdf.format(c.getTime()); String strR = iDay1 + "\n" + iMonth; return strR; } } /** * 最新揭晓时间显示规则 揭晓时间:如果是今天,显示今天12:34,如果是昨天,显示昨天 12:34,如果是其他日期,显示 06-08 12:34 *

* Title: getDateNewAnnounce *

* * @author cw * @date 2016年5月26日 上午8:30:43 * @return String *

* Description: *

* @return * */ public static String getDateNewAnnounce(long t) { Calendar c = Calendar.getInstance(); c.setTimeInMillis(t * 1000); long iDay = parseOldToCurrent(t); DateFormat sdf = new SimpleDateFormat("HH:mm", Locale.CHINESE); if (iDay == 0) { return "今天" + sdf.format(c.getTime()); } else if (iDay == 1) { return "昨天" + sdf.format(c.getTime()); } else { sdf = new SimpleDateFormat("MM-dd HH:mm"); return sdf.format(c.getTime()); } } public static String getDateNewAnnounceBill(long t) { Date dt = new Date(); Long time = dt.getTime(); Long i = time - t * 1000; Long j = (long) 86400000; int chage = (int) (i / j); if (chage < 1) { if (i / 3600000 >= 1) { if (i / 3600000 < 10) { return i / 3600000 + "小时前"; } else { Date d = new Date(i); SimpleDateFormat sdf = new SimpleDateFormat("HH"); return i / 3600000 + "小时前"; } } else { /* if (i < 60000) { return "刚刚"; } else {*/ if (i < 600000) { Date d = new Date(i); SimpleDateFormat sdf = new SimpleDateFormat("m"); return sdf.format(d) + "分钟前"; } else { Date d = new Date(i); SimpleDateFormat sdf = new SimpleDateFormat("mm"); return sdf.format(d) + "分钟前"; } //} } } /* else if (parseOldToCurrent(t)==1) { Date d = new Date(t * 1000); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); return "昨天" + sdf.format(d); } */ else { Date d = new Date(t * 1000); SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm"); return sdf.format(d); } } /** * 支付可用红包列表 *

* Title: getDateShowOff *

* * @author cw * @date 2016年5月27日 下午5:18:41 * @return String *

* Description: *

* @param t * @return * */ public static String getRedPacketExpire(long createTime) { long lDay = parseCurrentToFuture(createTime) + 1; if (lDay == 1) { return "今天后过期"; } else { return lDay + "天后过期"; } } public static String toDate(Object now) { if (null == now || null == now.toString() || JSONObject.NULL == now) { return ""; } DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(Long.parseLong(now.toString())); return formatter.format(calendar.getTime()); } public static String toDateSSS1000(Object now){ if ( null == now || null == now.toString() || JSONObject.NULL==now) { return ""; } DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(Long.parseLong(now.toString())*1000); return formatter.format(calendar.getTime()); } public static String toDateSSS(Object now) { if (null == now || null == now.toString() || JSONObject.NULL == now) { return ""; } DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(Long.parseLong(now.toString())); return formatter.format(calendar.getTime()); } public static String toDateMm(Object now) { if (null == now || null == now.toString() || JSONObject.NULL == now) { return ""; } DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(Long.parseLong(now.toString()) * 1000); return formatter.format(calendar.getTime()); } public static String toDateMm1(Object now) { if (null == now || null == now.toString() || JSONObject.NULL == now) { return ""; } DateFormat formatter = new SimpleDateFormat("MM-dd HH:mm:ss:SSS"); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(Long.parseLong(now.toString())); return formatter.format(calendar.getTime()); } public static String toDateSS(Object now) { if (null == now || null == now.toString() || JSONObject.NULL == now) { return ""; } DateFormat formatter = new SimpleDateFormat("mm:ss:SSS"); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(Long.parseLong(now.toString())); return formatter.format(calendar.getTime()).substring(0, 8); } public static String toDateSecond(Object now) { if (null == now || null == now.toString() || JSONObject.NULL == now) { return ""; } DateFormat formatter = new SimpleDateFormat("HH:mm:ss"); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(Long.parseLong(now.toString())); return formatter.format(calendar.getTime()).substring(0, 8); } public static String toDateMin(Object now) { if (null == now || null == now.toString() || JSONObject.NULL == now) { return ""; } DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm"); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(Long.parseLong(now.toString()) * 1000); return formatter.format(calendar.getTime()); } public static String toDateMin2(Object now) { if (null == now || null == now.toString() || JSONObject.NULL == now) { return ""; } DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm"); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(Long.parseLong(now.toString())); return formatter.format(calendar.getTime()); } public static String toDateSimplay(Object now) { if (null == now || null == now.toString() || JSONObject.NULL == now) { return ""; } DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(Long.parseLong(now.toString()) * 1000); return formatter.format(calendar.getTime()); } public static String toDateFormat(Object now, String strFormat) { if (null == now || null == now.toString() || JSONObject.NULL == now) { return ""; } DateFormat formatter = new SimpleDateFormat(strFormat); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(Long.parseLong(now.toString()) * 1000); return formatter.format(calendar.getTime()); } public static String toDate() { DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar calendar = Calendar.getInstance(); return formatter.format(calendar.getTime()); } public static String toDate(String format) { DateFormat formatter = new SimpleDateFormat(format); Calendar calendar = Calendar.getInstance(); return formatter.format(calendar.getTime()); } public static String toDateMinShow(Object now) { if (null == now || null == now.toString() || JSONObject.NULL == now) { return ""; } DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(Long.parseLong(now.toString()) * 1000); return formatter.format(calendar.getTime()); } }

 

package com.example.administrator.yyy;


import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;


@SuppressLint("AppCompatCustomView")
public class TimeTextView extends TextView  {
   
   
   public enum eDownTimeType{
      lottery//开奖倒计时
      ,quisoccer//虚拟足球开场倒计时
      ,activity//首页活动倒计时
      ,gambling//幸运4选1和快乐猜大小倒计时
   }
   
   public static final int HOUR = 1;
   public static final int MINUTE = 2;
   public static final int QUIZMINUTE = 3;

   public interface TimeFinishListener {
      void timeFinish();
      void timeTick(boolean bReturn);
   }
   
   private boolean run = false; // 是否启动了
   private TimeFinishListener mTimeFinishListener;
   private CountDownTimerUtils countDownTimerUtils;

   public TimeTextView(Context context, AttributeSet attrs) {
      super(context, attrs);
      initView(context, attrs);
   }

   public TimeTextView(Context context, AttributeSet attrs, int defStyle) {
      super(context, attrs, defStyle);
      initView(context, attrs);
   }
   
   public void setmTimeFinishListener(TimeFinishListener mTimeFinishListener) {
      this.mTimeFinishListener = mTimeFinishListener;
   }

   public TimeTextView(Context context) {
      super(context);
   }

   private void initView(Context context, AttributeSet attrs) {
      
   }


   public boolean isRun() {
      return run;
   }

   public void setRun(boolean run) {
      this.run = run;
   }

   /**
    * 共同倒计时
    * @param truetime 倒计时开始时间
    */
   public void startCommon(long truetime,long interval,eDownTimeType downTimeType) {
      if (!isRun()){
          setRun(true);
          onStartCommon(truetime, interval, downTimeType);
       }
   }
   
   /**
    * 开奖倒计时
    * @param downtime 倒计时开始时间
    * @param truetime 真实倒计时开始时间
    */
   public void startLottery(long truetime,long downtime,long timeCha) {
      if (!isRun()){
          setRun(true);
          onStartLottery(truetime, downtime, timeCha);
       }
   }
   
   
   public void cancel(){
      if(countDownTimerUtils!=null){
         countDownTimerUtils.cancel();
         setRun(false);
      }
   }
   int iCountDownInterval = 0;
   public void onStartLottery(final long truetime,long downtime,final long timeCha){
      iCountDownInterval = 0;
      countDownTimerUtils = new CountDownTimerUtils(downtime, 10L, new CountDownTimerUtils.CountDownTimerUtilsListener() {
         @Override
         public void onTick(long millisUntilFinished) {
            long currentTimeMillis = System.currentTimeMillis()+timeCha;
            if(truetime

 




    

        

            
         
               
   
               
            
        

        

        
            
            
            
        
        

            

            

            
        
    

    
     

    

        

        
    

    

        

        

            

            

            
        

        

            

            

            
        

    

    

    


        
    

核心的已经给上去了,剩下的就是资源图片和 颜色了。自己改改就行。  

下面是传送门:去我的csdn下载吧。完成的,直接运行就能看。

https://download.csdn.net/download/qq_35874340/11214495

你可能感兴趣的:(Android----机选摇一摇,猜大小功能)