2012-09-04 79 views
0

我做了一個腳本,檢測是否有互聯網連接:延遲super.onbackpressed在android系統

public static boolean isOnline() { 
    try { 
     InetAddress.getByName("google.hu").isReachable(3); 
     return true; 
    } catch (UnknownHostException e){ 
     return false; 
    } catch (IOException e){ 
     return false; 
    } 
} 

如果沒有互聯網的應用程序將警告用戶和退出!但是如何將super.onBackPressed延遲20秒? :)

this.toast1 = new Toast(getApplicationContext()); 
    toast1.setGravity(Gravity.CENTER, 0, 0); 
    toast1.setDuration(20000); 
    toast1.setView(layout); 
    toast1.show(); 
    super.onBackPressed(); 

回答

1
Thread delayThread= new Thread(new Runnable() 
       { 
        @Override 
        public void run() 
         { 
          try 
       { 
        Thread.sleep(1000); 
       } 
      catch (InterruptedException e) 
       { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 

          activityInstance.this.runOnUiThread(new Runnable() 
           { 
            @Override 
            public void run() 
             { 
              super.onBackPressed(); 
             } 
           }); 
         } 
       }); 
      delayThread.start(); 
+0

爲什麼會出現d.start? :) – user1632298

+0

和4.0 android不支持線程。 – user1632298

+0

'd.start()'應該是'delayThread.start()'。當然Android 4.0支持'Thread',你爲什麼認爲它不?此外,這個線程睡1秒不是20,所以你應該使用'Thread.sleep(20000)'。你不想調用'super.onBackPressed()',你應該在activity上調用'finish()'。 –

0

最簡單的是onCreate()創建Handler和使用postDelayed()Runnable調用super.onBackPressed()