[android小知识]removeCallbacks与postDelayed的恩怨史(removeCallbacks所谓的无效, View和Handler 的postDelayed)

常见的.postDelayed(runnable, time)方法就是常见的延迟处理的方法之一,postDelayed(mRun,time);当想要需要取消的时候,调用removeCallbacks(mRun);即可,就可以取消postDelayed的方法里面的runnable,当然如果里面runnable已经执行了,那就不可能撤回或者中止了。

http://blog.csdn.net/bluewindtalker/article/details/51984300

下面是布局文件

<span style="font-size:18px;"> <Button
                android:id="@+id/btn_demo_removecallback_start"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="开始postdelayed" />

            <Button
                android:id="@+id/btn_demo_removecallback_stop"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="测试removecallback" />

            <TextView
                android:id="@+id/tv_demo_removecallback_test_onAnimationEnd"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="测试removecallback runnable效果" /></span>

以下是测试代码。

<span style="font-size:18px;">final TextView mRemovecallbackTV = (TextView)findViewById(R.id.tv_demo_removecallback_test_onAnimationEnd);

         mRun = new Runnable() {
            @Override
            public void run() {
                if(DirectionMarqueeDemoActivity.this.isFinishing()){
                    BlueLog.e(TAG,"DirectionMarqueeDemoActivity  isFinishing ");
                    mMarqueeAnimationTV.clearAnimation();
                    mRemovecallbackTV.removeCallbacks(mRun);
                }
                BlueLog.e(TAG, "Runnable   " + DirectionMarqueeDemoActivity.this);
                mRemovecallbackTV.postDelayed(this, 3000);
            }
        };

        findViewById(R.id.btn_demo_removecallback_start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRemovecallbackTV.postDelayed(mRun, 3000);
                BlueLog.e(TAG, " postDelayed " );
            }
        });
        findViewById(R.id.btn_demo_removecallback_stop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRemovecallbackTV.removeCallbacks(mRun);
                BlueLog.e(TAG, "removeCallbacks ");
            }
        });</span>

其中mRun为Activity的成员变量。


运行的时候我们发现


即使activity 结束了调用了onDestory方法后这里仍然运行,问题在于代码中,先removeCallBacks,再postDelayed,这里加一个return就好,



正确的代码大家就在removeCallBacks加入return即可,下面是logcat的打印



所以如要要循环调用postDelayed的时候,一样要进行判断是否所属的activity已经退出了。将结束方法一定要体现出来



而postDelayed(runnable, time)有view.postDelayed(mRun, time);和new Handler().postDelayed(mRun,time);这两种,

对于view.postDelayed我们通过源码发现

 public boolean postDelayed(Runnable action, long delayMillis) {
        final AttachInfo attachInfo = mAttachInfo;
        if (attachInfo != null) {
            return attachInfo.mHandler.postDelayed(action, delayMillis);
        }
        // Assume that post will succeed later
        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
        return true;
    }
 return attachInfo.mHandler.postDelayed(action, delayMillis);最后进入了Handler的postDelayed

public final boolean postDelayed(Runnable r, long delayMillis)
    {
        return sendMessageDelayed(getPostMessage(r), delayMillis);
    }

而ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);进入ViewRootImpl.java中,

static final class RunQueue {
        private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();

        void post(Runnable action) {
            postDelayed(action, 0);
        }

        void postDelayed(Runnable action, long delayMillis) {
            HandlerAction handlerAction = new HandlerAction();
            handlerAction.action = action;
            handlerAction.delay = delayMillis;

            synchronized (mActions) {
                mActions.add(handlerAction);
            }
        }

        void removeCallbacks(Runnable action) {
            final HandlerAction handlerAction = new HandlerAction();
            handlerAction.action = action;

            synchronized (mActions) {
                final ArrayList<HandlerAction> actions = mActions;

                while (actions.remove(handlerAction)) {
                    // Keep going
                }
            }
        }

        void executeActions(Handler handler) {
            synchronized (mActions) {
                final ArrayList<HandlerAction> actions = mActions;
                final int count = actions.size();

                for (int i = 0; i < count; i++) {
                    final HandlerAction handlerAction = actions.get(i);
                    handler.postDelayed(handlerAction.action, handlerAction.delay);
                }

                actions.clear();
            }
        }

最后仍然执行了handler.postDelayed(handlerAction.action, handlerAction.delay),所以两个内容是相差无几的。


其中HandlerAction来自于view调用invalidate时,父View传入的。



  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
应用启动页自定义跳转计时器View Demo: CircleTextProgressbar.java: package com.demo.startpageskiptimerdemo.widget; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.RectF; import android.text.TextUtils; import android.util.AttributeSet; import com.demo.startpageskiptimerdemo.R; /** * Created by Administrator on 2016/8/26. (自定义TextView,用于欢迎页跳过图标) */ public class CircleTextProgressbar extends android.support.v7.widget.AppCompatTextView { /** * 外部轮廓的颜色。 */ private int outLineColor = Color.BLACK; /** * 外部轮廓的宽度。 */ private int outLineWidth = 2; /** * 内部圆的颜色。 */ private ColorStateList inCircleColors = ColorStateList.valueOf(Color.TRANSPARENT); /** * 中心圆的颜色。 */ private int circleColor; /** * 进度条的颜色。 */ private int progressLineColor = Color.WHITE; /** * 进度条的宽度。 */ private int progressLineWidth = 8; /** * 画笔。 */ private Paint mPaint = new Paint(); /** * 进度条的矩形区域。 */ private RectF mArcRect = new RectF(); /** * 进度。 */ private int progress = 100; /** * 进度条类型。 */ private ProgressType mProgressType = ProgressType.COUNT; /** * 进度倒计时时间。 */ private long timeMillis = 5000; /** * View的显示区域。 */ final Rect bounds = new Rect(); /** * 进度条通知。 */ private OnCountdownProgressListener mCountdownProgressListener; /** * Listener what。 */ private int listenerWhat = 0; private String seconds; public CircleTextProgressbar(Context context) { this(context, null); } public CircleTextProgressbar(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CircleTextProgressbar(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initialize(context, attrs); } public void setSeconds(String seconds) { this.seconds = seconds; invalidate(); } /** * 初始化。 * * @param context 上下文。 * @param attributeSet 属性。 */ private void initialize(Context context, AttributeSet attributeSet) { mPaint.setAntiAlias(true); TypedArray typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.CircleTextProgressbar); if (typedArray.hasValue(R.styleable.CircleTextProgressbar_in_circle_color)) inCircleColors = typedArray.getColorStateList(R.styleable.CircleTextProgressbar_in_circle_color); else inCircleColors = ColorStateList.valueOf(Color.TRANSPARENT); circleColor = inCircleColors.getColorForState(getDrawableState(), Color.TRANSPARENT); typedArray.recycle(); } /** * 设置外部轮廓的颜色。 * * @param outLineColor 颜色值。 */ // public void setOutLineColor(@ColorInt int outLineColor) { public void setOutLineColor(int outLineColor) { this.outLineColor = outLineColor; invalidate(); } /** * 设置外部轮廓的颜色。 * * @param outLineWidth 颜色值。 */ // public void setOutLineWidth(@ColorInt int outLineWidth) { public void setOutLineWidth(int outLineWidth) { this.outLineWidth = outLineWidth; invalidate(); } /** * 设置圆形的填充颜色。 * * @param inCircleColor 颜色值。 */ // public void setInCircleColor(@ColorInt int inCircleColor) { public void setInCircleColor(int inCircleColor) { this.inCircleColors = ColorStateList.valueOf(inCircleColor); invalidate(); } /** * 是否需要更新圆的颜色。 */ private void validateCircleColor() { int circleColorTemp = inCircleColors.getColorForState(getDrawableState(), Color.TRANSPARENT); if (circleColor != circleColorTemp) { circleColor = circleColorTemp; invalidate(); } } /** * 设置进度条颜色。 * * @param progressLineColor 颜色值。 */ // public void setProgressColor(@ColorInt int progressLineColor) { public void setProgressColor(int progressLineColor) { this.progressLineColor = progressLineColor; invalidate(); } /** * 设置进度条线的宽度。 * * @param progressLineWidth 宽度值。 */ public void setProgressLineWidth(int progressLineWidth) { this.progressLineWidth = progressLineWidth; invalidate(); } /** * 设置进度。 * * @param progress 进度。 */ public void setProgress(int progress) { this.progress = validateProgress(progress); invalidate(); } /** * 验证进度。 * * @param progress 你要验证的进度值。 * @return 返回真正的进度值。 */ private int validateProgress(int progress) { if (progress > 100) progress = 100; else if (progress < 0) progress = 0; return progress; } /** * 拿到此时的进度。 * * @return 进度值,最大100,最小0。 */ public int getProgress() { return progress; } /** * 设置倒计时总时间。 * * @param timeMillis 毫秒。 */ public void setTimeMillis(long timeMillis) { this.timeMillis = timeMillis; invalidate(); } /** * 拿到进度条计时时间。 * * @return 毫秒。 */ public long getTimeMillis() { return this.timeMillis; } /** * 设置进度条类型。 * * @param progressType {@link ProgressType}. */ public void setProgressType(ProgressType progressType) { this.mProgressType = progressType; resetProgress(); invalidate(); } /** * 重置进度。 */ private void resetProgress() { switch (mProgressType) { case COUNT: progress = 0; break; } } /** * 拿到进度条类型。 * * @return */ public ProgressType getProgressType() { return mProgressType; } /** * 设置进度监听。 * * @param mCountdownProgressListener 监听器。 */ public void setCountdownProgressListener(int what, OnCountdownProgressListener mCountdownProgressListener) { this.listenerWhat = what; this.mCountdownProgressListener = mCountdownProgressListener; } /** * 开始。 */ public void start() { stop(); post(progressChangeTask); } /** * 重新开始。 */ public void reStart() { resetProgress(); start(); } /** * 停止。 */ public void stop() { removeCallbacks(progressChangeTask); } @Override protected void onDraw(Canvas canvas) { // 获取view的边界 getDrawingRect(bounds); int size = bounds.height() > bounds.width() ? bounds.width() : bounds.height(); float outerRadius = size / 2; // 画内部背景 int circleColor = inCircleColors.getColorForState(getDrawableState(), 0); mPaint.setStyle(Paint.Style.FILL); mPaint.setColor(circleColor); canvas.drawCircle(bounds.centerX(), bounds.centerY(), outerRadius - outLineWidth, mPaint); // 画边框圆 mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeWidth(outLineWidth); mPaint.setColor(outLineColor); canvas.drawCircle(bounds.centerX(), bounds.centerY(), outerRadius - outLineWidth / 2, mPaint); // 画字 Paint paint = getPaint(); paint.setColor(getCurrentTextColor()); paint.setAntiAlias(true); paint.setTextAlign(Paint.Align.CENTER); float textY = bounds.centerX(); float textS = (bounds.bottom + paint.ascent() / 2) - 10; if (!TextUtils.isEmpty(seconds)) canvas.drawText(seconds, bounds.centerX(), textS, paint); canvas.drawText(getText().toString(), bounds.centerX(), textY, paint); // 画进度条 mPaint.setColor(progressLineColor); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeWidth(progressLineWidth); mPaint.setStrokeCap(Paint.Cap.ROUND); int deleteWidth = progressLineWidth + outLineWidth; mArcRect.set(bounds.left + deleteWidth / 2, bounds.top + deleteWidth / 2, bounds.right - deleteWidth / 2, bounds.bottom - deleteWidth / 2); canvas.drawArc(mArcRect, 270, 360 * progress / 100, false, mPaint); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int lineWidth = 4 * (outLineWidth + progressLineWidth); int width = getMeasuredWidth(); int height = getMeasuredHeight(); int size = (width > height ? width : height) + lineWidth; setMeasuredDimension(size, size); } @Override protected void drawableStateChanged() { super.drawableStateChanged(); validateCircleColor(); } /** * 进度更新task。 */ private Runnable progressChangeTask = new Runnable() { @Override public void run() { removeCallbacks(this); switch (mProgressType) { case COUNT: progress += 1; break; } if (progress >= 0 && progress <= 100) { if (mCountdownProgressListener != null) mCountdownProgressListener.onProgress(listenerWhat, progress); invalidate(); postDelayed(progressChangeTask, timeMillis / 100); } else progress = validateProgress(progress); } }; /** * 进度条类型。 */ public enum ProgressType { /** * 顺数进度条,从0-100; */ COUNT, } /** * 进度监听。 */ public interface OnCountdownProgressListener { /** * 进度通知。 * * @param progress 进度值。 */ void onProgress(int what, int progress); } } attrs.xml: <?xml version="1.0" encoding="utf-8"?> <resources> <!-- 欢迎页跳过按钮样式 --> <declare-styleable name="CircleTextProgressbar"> <attr name="in_circle_color" format="color" /> <attr name="cenerTextSie" format="dimension"></attr> <attr name="secondsTextSize" format="dimension"></attr> <attr name="secondsText" format="string"></attr> </declare-styleable> </resources> StartPageActivity.java: package com.demo.startpageskiptimerdemo.activity; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import com.bumptech.glide.Glide; import com.bumptech.glide.signature.StringSignature; import com.demo.startpageskiptimerdemo.R; import com.demo.startpageskiptimerdemo.widget.CircleTextProgressbar; import java.util.Timer; import java.util.TimerTask; /** * 启动页面 * * @author chenke * @time 2017/12/7 10:13 * @mail [email protected] */ public class StartPageActivity extends AppCompatActivity implements View.OnTouchListener { private final static String TAG = "StartPageActivity"; CircleTextProgressbar mTvSkip; ImageView mStartPageImag; LinearLayout skipLayout; RelativeLayout welBgRlay; // 倒计时timer private Timer timer; // 启动页图片地址 private String imgUrl = "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1851053687,4000575540&fm=27&gp=0.jpg"; private int waitTime = 5;// 时长5秒 Handler mHandler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message message) { switch (message.what) { case 1: gotoHomeActivity(); break; } return false; } }); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_start_page); init(); } private void init() { mTvSkip = (CircleTextProgressbar) findViewById(R.id.tv_red_skip); mStartPageImag = (ImageView) findViewById(R.id.star_page_icon); skipLayout = (LinearLayout) findViewById(R.id.skip_layout); welBgRlay = (RelativeLayout) findViewById(R.id.start_goadvert_lay); mTvSkip.setOutLineColor(Color.TRANSPARENT); mTvSkip.setInCircleColor(Color.parseColor("#AAC6C6C6")); mTvSkip.setProgressColor(Color.WHITE); mTvSkip.setProgressLineWidth(5); // 开始时计 mCountDowntimer(); mTvSkip.reStart(); // 设置skipLayout浮在整个页面的最上层 welBgRlay.bringChildToFront(skipLayout); mTvSkip.setOnTouchListener(this); mStartPageImag.setOnTouchListener(this); // 加载图片 if (!TextUtils.isEmpty(imgUrl)) { Glide.with(this).load(imgUrl).signature(new StringSignature("1")).into (mStartPageImag); } } @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { if (null != timer) { timer.cancel(); timer = null; } switch (view.getId()) { case R.id.star_page_icon: // 广告 //********** 跳转网页 (进入启动页面广告详情)*********** break; case R.id.tv_red_skip: // 跳转计时view if (null != timer) { timer.cancel(); timer = null; } mHandler.sendEmptyMessage(1); return true; } } return false; } /** * 进入首页 */ public void gotoHomeActivity() { Intent homeIntent = new Intent(); homeIntent.setClass(this, MainActivity.class); startActivity(homeIntent); finish(); } /** * 计时器 */ private void mCountDowntimer() { timer = new Timer(); mTvSkip.setSeconds(waitTime + "s"); timer.schedule(task, 1000, 1000); } /** * 计时器线程 */ TimerTask task = new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { // UI thread @Override public void run() { waitTime--; mTvSkip.setSeconds(waitTime + "s"); if (waitTime <= 0) { if (null != timer) { timer.cancel(); timer = null; } mHandler.sendEmptyMessage(1); } } }); } }; } activity_start_page.xml: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/start_goadvert_lay" android:layout_width="match_parent" android:layout_height="match_parent" android: <ImageView android:id="@+id/star_page_icon" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:scaleType="fitXY" /> <LinearLayout android:id="@+id/skip_layout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:gravity="center" android:orientation="horizontal" android:paddingRight="10dp" android:paddingTop="10dp" android:visibility="visible"> <com.demo.startpageskiptimerdemo.widget.CircleTextProgressbar android:id="@+id/tv_red_skip" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="跳过" android:textColor="@android:color/white" android:textSize="10dp" /> </LinearLayout> </RelativeLayout> styles.xml: <resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> <!--启动页面跳过按钮自定义style--> <style name="CustomProgressStyle" parent="@android:style/Widget.ProgressBar.Large"> <item name="android:minWidth">35dip</item> <item name="android:maxWidth">35dip</item> <item name="android:minHeight">35dip</item> <item name="android:maxHeight">35dip</item> </style> </resources> AndroidManifest.xml中添加请求网络权限: <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> build.gradle中dependencies添加: // 异步加载图片 compile 'com.github.bumptech.glide:glide:3.7.0' compile 'com.android.support:support-v4:23.3.0'
package com.zhy.view; import android.content.Context; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.zhy.ccbCricleMenu.R; public class CircleMenuLayout extends ViewGroup { /** * layout的半径 */ private int mRadius; private float mMaxChildDimesionRadio = 1 / 4f; private float mCenterItemDimesionRadio = 1 / 3f; private LayoutInflater mInflater; private double mStartAngle = 0; private String[] mItemTexts = new String[] { "安全中心 ", "特色服务", "投资理财", "转账汇款", "我的账户", "信用卡" }; private int[] mItemImgs = new int[] { R.drawable.home_mbank_1_normal, R.drawable.home_mbank_2_normal, R.drawable.home_mbank_3_normal, R.drawable.home_mbank_4_normal, R.drawable.home_mbank_5_normal, R.drawable.home_mbank_6_normal }; private int mTouchSlop; /** * 加速度检测 */ private float mDownAngle; private float mTmpAngle; private long mDownTime; private boolean isFling; public CircleMenuLayout(Context context, AttributeSet attrs) { super(context, attrs); mInflater = LayoutInflater.from(context); for (int i = 0; i < mItemImgs.length; i++) { final int j = i; View view = mInflater.inflate(R.layout.turnpalte_inner_view, this, false); ImageView iv = (ImageView) view .findViewById(R.id.id_circle_menu_item_image); TextView tv = (TextView) view .findViewById(R.id.id_circle_menu_item_text); iv.setImageResource(mItemImgs[i]); tv.setText(mItemTexts[i]); view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getContext(), mItemTexts[j], Toast.LENGTH_SHORT).show(); } }); addView(view); } mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(getSuggestedMinimumWidth(), getSuggestedMinimumHeight()); // 获得半径 mRadius = Math.max(getWidth(), getHeight()); final int count = getChildCount(); // Log.e("TAG", count + ""); int childSize = (int) (mRadius * mMaxChildDimesionRadio); int childMode = MeasureSpec.EXACTLY; for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } int makeMeasureSpec = -1; if (child.getId() == R.id.id_circle_menu_item_center) { makeMeasureSpec = MeasureSpec.makeMeasureSpec( (int) (mRadius * mCenterItemDimesionRadio), childMode); } else { makeMeasureSpec = MeasureSpec.makeMeasureSpec(childSize, childMode); } child.measure(makeMeasureSpec, makeMeasureSpec); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int layoutWidth = r - l; int layoutHeight = b - t; int layoutRadius = Math.max(layoutWidth, layoutHeight); // Laying out the child views final int childCount = getChildCount(); int left, top; int radius = (int) (layoutRadius * mMaxChildDimesionRadio); float angleDelay = 360 / (getChildCount() - 1); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (child.getId() == R.id.id_circle_menu_item_center) continue; if (child.getVisibility() == GONE) { continue; } mStartAngle %= 360; float tmp = layoutRadius * 1f / 3 - 1 / 22f * layoutRadius; left = layoutRadius / 2 + (int) Math.round(tmp * Math.cos(Math.toRadians(mStartAngle)) - 1 / 2f * radius); top = layoutRadius / 2 + (int) Math.round(tmp * Math.sin(Math.toRadians(mStartAngle)) - 1 / 2f * radius); // Log.e("TAG", "left = " + left + " , top = " + top); child.layout(left, top, left + radius, top + radius); mStartAngle += angleDelay; } View cView = findViewById(R.id.id_circle_menu_item_center); cView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getContext(), "you can do something just like ccb ", Toast.LENGTH_SHORT).show(); } }); // Log.e("TAG", // cView.getMeasuredWidth() + " , " + cView.getMeasuredWidth()); int cl = layoutRadius / 2 - cView.getMeasuredWidth() / 2; int cr = cl + cView.getMeasuredWidth(); cView.layout(cl, cl, cr, cr); } private float mLastX; private float mLastY; private FlingRunnable mFlingRunnable; // @Override // public boolean onTouchEvent(MotionEvent event) // { // } @Override public boolean dispatchTouchEvent(MotionEvent event) { float x = event.getX(); float y = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mLastX = x; mLastY = y; mDownAngle = getAngle(x, y); mDownTime = System.currentTimeMillis(); mTmpAngle = 0; if (isFling) { removeCallbacks(mFlingRunnable); isFling = false; return true ; } break; case MotionEvent.ACTION_MOVE: float start = getAngle(mLastX, mLastY); float end = getAngle(x, y); // Log.e("TAG", "start = " + start + " , end =" + end); if (getQuadrant(x, y) == 1 || getQuadrant(x, y) == 4) { mStartAngle += end - start; mTmpAngle += end - start; } else { mStartAngle += start - end; mTmpAngle += start - end; } // rotateButtons((float) (mStartAngle - currentAngle)); requestLayout(); mLastX = x; mLastY = y; break; case MotionEvent.ACTION_UP: float anglePrMillionSecond = mTmpAngle * 1000 / (System.currentTimeMillis() - mDownTime); Log.e("TAG", anglePrMillionSecond + " , mTmpAngel = " + mTmpAngle); if (Math.abs(anglePrMillionSecond) > 230 && !isFling) { post(mFlingRunnable = new FlingRunnable(anglePrMillionSecond)); } if(Math.abs(anglePrMillionSecond) >230 || isFling) { return true ; } break; } return super.dispatchTouchEvent(event); } private float getAngle(float xTouch, float yTouch) { double x = xTouch - (mRadius / 2d); double y = yTouch - (mRadius / 2d); return (float) (Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI); } private int getQuadrant(float x, float y) { int tmpX = (int) (x - mRadius / 2); int tmpY = (int) (y - mRadius / 2); if (tmpX >= 0) { return tmpY >= 0 ? 4 : 1; } else { return tmpY >= 0 ? 3 : 2; } } private class FlingRunnable implements Runnable { private float velocity; public FlingRunnable(float velocity) { this.velocity = velocity; } public void run() { if ((int) Math.abs(velocity) < 20) { isFling = false; return; } isFling = true; // rotateButtons(velocity / 75); mStartAngle += (velocity / 30); velocity /= 1.0666F; postDelayed(this, 30); requestLayout(); Log.e("TAG", velocity + ""); } } }
mMediaPlayer.prepare(); Log.v(TAG,"==mRecordPath==="+mRecordPath+"=mAccompanyPath=="+mAccompanyPath); mAccompany = new FileInputStream(mAccompanyPath); mRecord = new FileOutputStream(mRecordPath); mAccompany.read(header); // mRecord.write(header); mMediaPlayer.start(); mAudioRecord.startRecording(); mUpdateProgressHandler.post(mUpdateProgressRunnable); // 边录音边混合 while (isRunning) { Log.v("H3c", "run=============================================="); int rSize = mAudioRecord.read(recordBuf, 0, RecorderParameter.bufferSizeInBytes); Log.v("H3c", "go:" + rSize); int size = mAccompany.read(accompanyBuf, 0, RecorderParameter.bufferSizeInBytes); Log.v("H3c", "s:" + size); if (size < 0) { isRunning = false; Log.v("H3c", "run======isRunning======="+isRunning); continue; } byte[] mixBuff = new byte[size]; //播放一包录音 if(null != audioTrack){ audioTrack.write(recordBuf, 0, rSize); } for (int i = 0; i < size; i++) { mixBuff[i] = (byte) Math .round((accompanyBuf[i] + recordBuf[i]) / 2); } mRecord.write(mixBuff); } } catch (IOException e) { Log.v("H3c", "=====catch==="+e); e.printStackTrace(); } finally { Log.v("H3c", "=====final====="+isRunning); if (mMediaPlayer != null) { mMediaPlayer.stop(); } if (mAudioRecord != null) { mAudioRecord.stop(); } if(null != audioTrack){ audioTrack.stop(); } try { mAccompany.close(); mRecord.close(); } catch (IOException e) { e.printStackTrace(); } mUpdateProgressHandler .removeCallbacks(mUpdateProgressRunnable); // RemoveFile(mRecordPath); } copyWaveFile(mRecordPath, SavaAudioPath); RemoveFile(mRecordPath); Log.e("H3c", "end");

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值