在此活动中,我使用Runnable
在按下Button
时旋转图像。
问题是,在我终止整个应用程序后,当我再次启动我的应用程序时,此活动会提前。我了解到,当回调被错误地删除时会发生这种情况。
我的问题:如何修复此代码以正确删除所有回调并避免在错误的时刻重新打开活动。
public class MatchTimeActivity extends Activity {
Button MatchTime;
TextView Header1;
ImageView Face;
Timer myTimer;
private Handler matchHandler;
private Runnable matchAction;
public final static String match_int_value1="com.planis.matchthetime.match_int_value1";
public final static String match_int_value2="com.planis.matchthetime.match_int_value2";
@Override
public void onBackPressed() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_match_time);
MatchTime = (Button) findViewById(R.id.MatchTimeButton);
Header1 = (TextView) findViewById(R.id.MatchTimeHeader);
Typeface custom_font2 = Typeface.createFromAsset(getAssets(), "fonts/font1.ttf");
MatchTime.setTypeface(custom_font2);
Header1.setTypeface(custom_font2);
matchHandler = new Handler();
matchAction = new Runnable() {
@Override public void run() {
Face = (ImageView) findViewById(R.id.MatchTimeImage);
Face.setRotation(Face.getRotation()+9);
matchHandler.postDelayed(this, 25);
}
};
ListenTo();
}
public void onStop(){
super.onStop();
finish();
}
public void ListenTo(){
MatchTime.setOnTouchListener(new OnTouchListener(){
long time_start=0;
long time_end=0;
@Override
public boolean onTouch(View view, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN ) {
time_start=System.currentTimeMillis();
matchHandler.post(matchAction);
return true;
}
if (event.getAction() == MotionEvent.ACTION_UP ) {
time_end=System.currentTimeMillis();
long TimeCounted=time_end-time_start;
matchHandler.removeCallbacksAndMessages(null);
matchHandler = null;
SaveAndSend(TimeCounted);
return true;
}
return false;
}
});
}
public void SaveAndSend(long TimeCountedlong){
int TimeCountedint=(int)(long) TimeCountedlong;
Intent intent = getIntent();
int TimeToMatchsas = intent.getIntExtra("display_int_value",0);
Intent intent2 = new Intent(this, ResultsActivity.class);
intent2.putExtra("match_int_value1", TimeToMatchsas);
intent2.putExtra("match_int_value2", TimeCountedint);
startActivity(intent2);
finish();
}
}
答案 0 :(得分:2)
你需要挂钩onPause()
并清理你的回调,然后暂停活动并最终销毁。
@Override
public void onPause() {
matchHandler.removeCallbacksAndMessages(null);
super.onPause();
}