2016-09-16 72 views
0

我有應用程序與計時器。當我按下電源按鈕時,我的應用進入睡眠模式並停止計時。我應該怎麼做計時器繼續工作。下面我非常簡單的代碼計時器。Android應用不能在睡眠模式下工作

Thread t = new Thread(){ 
    @Override 
    public void run() { 
     while (!isInterrupted()){ 
      try { 
       Thread.sleep(1000); 
       i++; 
       Log.e("pokaz "," i "+i); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
}; 
+2

看看這個:http://stackoverflow.com/questions/10725711/how-to-do-not-let-thread-stop-theme-self-when-in-standby-mode – 476rick

回答

0

我解決了我的問題。我寫在活動

PowerManager pm; 
    PowerManager.WakeLock wl; 
    pm = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE); 
    wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag"); 
    wl.acquire(); 

和佈局這個代碼編寫代碼

android:keepScreenOn="true" 

但現在我的應用程序在後臺和版本API是奇巧evrything是確定的。當在API lolipop中測試我的應用程序並進入睡眠模式,然後打開手機時,我看到消息「不幸myApp已停止」。爲什麼?

-1

若要您的應用程序在後臺,你需要使用ServiceIntentServiceBroadCastReceiver

而你的線程工作Service