2013-04-23 63 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(); 
} 

,而這將在您的活動去前臺和其他活動出現停止振動器(例如來電您活動在前臺)。這可能比僅在應用完成時取消振動器更爲理想。

相關問題