2013-04-23 60 views
1

我需要在用户退出应用程序后停止我的应用程序正在做的所有操作(如振动),我该怎么做?我的应用在手机振动一段时间,用户选择,但如果用户启动,并退出应用程序..手机继续振动的时间选择..我该如何对待这个错误?当用户离开应用程序时无法完成执行完成

public class MainActivity extends Activity { 
    EditText tempo; 
    Button bt; 
    Thread t; 
    int estado = 1; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     tempo = (EditText) findViewById(R.id.tempo); 
     //long delay = Long.parseLong(tempo.getText().toString()); 

     bt = (Button) findViewById(R.id.btvibrar); 

     bt.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View arg0) { 

       if (!tempo.getText().toString().equals("")) { 

        if (estado == 1) { 

         Vibrar(); 
         estado *= -1; 

         bt.setText("Parar !"); 
         bt.setBackgroundColor(Color.RED); 

         //Handler handler = new Handler(); 
         //handler.postDelayed(new Runnable() { 

         //@Override 
         //public void run() { 
         //estado*=-1; 
         //bt.setText("Vibrar !"); 
         //bt.setBackgroundColor(Color.GREEN); 
         //} 
         // }, ); 
        } else { 
         Parar(); 
         estado *= -1; 
         bt.setText("Vibrar !"); 
         bt.setBackgroundColor(Color.GREEN); 
        } 
       } else { 
        AlertDialog.Builder dialogo = new AlertDialog.Builder(MainActivity.this); 
        dialogo.setTitle("Erro !"); 
        dialogo.setMessage("Escolha um tempo."); 
        dialogo.setNeutralButton("OK", null); 
        dialogo.show(); 

       } 
      } 

      private void Vibrar() { // É necessario lançar excessao no ANDROIDMANIFEST.XML 
       Vibrator rr = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); 
       long treal = Long.parseLong(tempo.getText().toString()); 
       long milliseconds = treal * 1000; 
       rr.vibrate(milliseconds); 
      } 

      private void Parar() { 
       Vibrator rr = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); 
       rr.cancel(); 
      } 
     }); 
    } 
} 

回答

1

首先,您需要区分退出和暂停应用程序(如果另一个应用程序到达前台,则会发生暂停)。其次,您需要重写适当的方法来处理应用程序暂停或销毁时发生的情况。

例如,覆盖

protected void onPause() {} 

将允许你定义应该发生什么,当应用程序被暂停,因此,你可以优雅地停止无论你的应用程序在做。

同样,如果需要,您可以实施onStoponDestroy。但是,在你的情况,我相信onStop和就足够了:)

另外,尽量给这个网页一看,它给人的生命周期活动的详细说明 http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

+0

使用OnPause()和Onstop()后退出应用程序,找到一个Bug,振动结束......但是当我退出并阻止手机时,使用振动器解锁手机,和电话“记住”我上次选择振动......并开始!如何完全结束振动器(和缓冲器?)? – Rcgoncalves 2013-04-24 02:09:45

0

你需要停止振动服务您的活动的onStop()

@Override 
protected void onStop() { 
      Vibrator rr = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); 
      rr.cancel(); 
    } 
0

从那里添加您ativity并取消振动器:

@Override 
public void onPause() { 
    Parar(); 
} 

,而这将在您的活动去前台和其他活动出现停止振动器(例如来电您活动在前台)。这可能比仅在应用完成时取消振动器更为理想。

相关问题