我试图从Android手机上按本机后退按钮时取消CountDownTimer。因此,我想覆盖onBackPressed方法,以取消计时器并返回到另一个活动,但只能执行一次。(返回主活动,如主页按钮)。
这是代码的一部分:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); if (getResources().getConfiguration().orientation== Configuration.ORIENTATION_LANDSCAPE){ ImageView und1=(ImageView)findViewById(R.id.undita1); ViewGroup.LayoutParams params = (ViewGroup.LayoutParams) und1.getLayoutParams(); params.height=150; und1.setLayoutParams(params); ImageView und2=(ImageView)findViewById(R.id.undita2); ViewGroup.LayoutParams params2 = (ViewGroup.LayoutParams) und2.getLayoutParams(); params2.height=150; und2.setLayoutParams(params2); ImageView und3=(ImageView)findViewById(R.id.undita3); ViewGroup.LayoutParams params3 = (ViewGroup.LayoutParams) und3.getLayoutParams(); params3.height=150; und3.setLayoutParams(params3); } mProgressBar=(ProgressBar)findViewById(R.id.progressBar); mProgressBar.setProgress(0); mCountDownTimer=new CountDownTimer(90000,1000) { int i=0; @Override public void onTick(long millisUntilFinished) { Log.v("Log_tag", "Tick of Progress" + i + millisUntilFinished); i++; mProgressBar.setProgress(i); } @Override public void onFinish() { i++; mProgressBar.setProgress(i); Intent in = new Intent(getApplicationContext(), MyActivity2.class); startActivity(in); } }; mCountDownTimer.start(); android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); Bundle b; b = getIntent().getExtras(); nivel= b.getInt("level"); TextView niv=(TextView) findViewById(R.id.Nivel); niv.setText("Level: "+ nivel); generare_3_diferente(nivel);} @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.my, menu); return true;} @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK)) { //Back key pressed mCountDownTimer.cancel(); Intent in = new Intent(getApplicationContext(), MyActivity2.class); startActivity(in); mCountDownTimer.cancel(); return true; }else{ return super.onKeyDown(keyCode, event); } } @Override public void onBackPressed(){ mCountDownTimer.cancel(); Intent in = new Intent(this, MyActivity2.class); startActivity(in); super.onBackPressed(); } }
onBackPressed应该在主活动类中
还尝试在应用的清单文件中指定父项和子项活动,例如
android:parentActivityName
并尝试使用类似的东西并重建您的应用程序
@Override public void onBackPressed() { super.onBackPressed(); i = new Intent(CurrentActivity.this, NextActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); finish(); }
如果仍然无法正常运行,请尝试制作一个新应用程序并导入文件