簡體   English   中英

類似於Java中C#的Process.Close事件?

[英]Similar to C#'s Process.Close event in Java?

如果我使用Java中的ProcessBuilder啟動進程,是否可以監聽該進程是否已關閉? 我想做的是啟動一個進程,在mySQL表中插入一條記錄,當進程被殺死或用戶退出時,然后在該mysql表中執行delete語句。 我已經在C#中完成了此操作,但是我的用戶要求該應用程序也能夠在linux和mac上運行,因此我堅持了這一部分。

試試這個我的朋友。

public class YourClass {

    public static void main(String[] args) throws IOException {

        ProcessBuilder  yourProcess = new ProcessBuilder(); 
        Process process = yourProcess.start();//Creates a new object containing your process
        //Your insert SQL stuff...
        try {
            process.waitFor();//Waits until the process finish
            //Your delete SQL stuff...
        } catch (InterruptedException ex) {
            System.out.println("The process finished unexpectly");;
        }            
    }
}

您可能可以使用一種Android生命周期,即onDestroy()方法,只需確保在其中一個事件上調用finish()即可。

另外,您還可以將finish()放在“警告對話框”按鈕上,當用戶按下登錄屏幕上的后退按鈕時,該按鈕會彈出。 您可能會添加onBackPressed()方法,然后您的最終代碼應如下所示:

 onDestroy(){
 super.onDestroy();
 //place your delete function here..
 }

 //then call this when user pressed home button or backbutton on login screen
 finish();

 //or
 onBackPressed(){
 //Show a dialog
 //then put the finish() function on the positive button of a dialog.
 dialog.setPositiveButton...{
 finish();
 }

只需確保在擁有onDestroy()方法時就使用了finish()函數,因為它將作為服務器的觸發,或者如果用戶電話超出其內存容量並且應用程序被迫終止,則可能會觸發該觸發器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM