[英]Running repeating animation in Android using a thread/runnable
My goal is to have a thread running that plays a sound then chooses a random animation and a random image and displays them. 我的目标是让一个正在运行的线程播放声音,然后选择一个随机动画和一个随机图像并显示它们。
It is currently working, but I was wondering if there is a better way. 它目前正在运行,但是我想知道是否有更好的方法。 I have a Hacker's understanding of threading (as in, I only know that this works), so I'd appreciate some feedback. 我对黑客对线程有一定的了解(例如,我只知道这是可行的),因此,我希望能得到一些反馈。 Also, I've been having issues with memory overflow in my app, is there a better way to manage this Activity memory-wise? 另外,我在应用程序中遇到内存溢出问题,是否有更好的方法来管理该Activity的内存? Thank you so much! 非常感谢!
public int[] images = {R.drawable.splat0,R.drawable.splat1,R.drawable.splat2,R.drawable.splat3,
R.drawable.splat4,R.drawable.splat5,R.drawable.splat6,R.drawable.splat7,R.drawable.splat8,
R.drawable.splat9};
public int[] anims= {R.anim.splat0,R.anim.splat1,R.anim.splat2,
R.anim.splat3,R.anim.splat4,R.anim.splat5,R.anim.splat6};
MediaManager mp;
Handler tick_Handler = new Handler();
MyThread tick_thread = new MyThread();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
MainActivity.this.setContentView(R.layout.activity_main);
mp = new MediaManager();
image = (ImageView)this.findViewById(R.id.mainActivitySplat);
tick_Handler.post(tick_thread);
}
@Override
public void onStop(){
tick_Handler.removeCallbacks(tick_thread);
super.onStop();
}
@Override
public void onResume(){
tick_Handler.post(tick_thread);
super.onResume();
}
private class MyThread implements Runnable {
@Override
public void run() {
mp.playSoundClip(MainActivity.this,R.raw.swoosh);
image.setBackgroundResource(images[(int)(Math.random()*splats.length)]);
Animation myAnim=AnimationUtils.loadAnimation(MainActivity.this,splatAnim[(int)(Math.random()*splatAnim.length)]);
splat.startAnimation(myAnim);
tick_Handler.postDelayed(tick_thread, 3500);
}
}
Edit: I have discovered this is a BAD way of using the Thread. 编辑:我发现这是使用线程的一种坏方法。 MyThread holds an implicit reference to the Activity, and causes a massive memory leak. MyThread持有对Activity的隐式引用,并导致大量内存泄漏。 By changing the class to private static MyThread I solve the leak, but I have not yet figured out how to get the desired behavior this way. 通过将类更改为私有静态MyThread,我解决了泄漏问题,但是我还没有弄清楚如何以这种方式获得所需的行为。 Will update later. 稍后将更新。
使用类似boolean isActibityKilled=true //when in onstop
的标志boolean isActibityKilled=true //when in onstop
中在可运行boolean isActibityKilled=true //when in onstop
使用它来检查活动是否正在运行,如果活动未在运行,或者它已停止,则杀死线程
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.