2011-03-13 59 views
7

我有此應用程序需要運行週期性發出嗶聲的服務(背景)。 手機需要每隔一分鐘嗶一聲,時間爲5秒(在服務中使用了一個處理程序)。我已經實現了這個完美的服務,但是當手機進入深度睡眠模式時,這個處理程序的執行停止。在SO中使用this答案,我設法使用喚醒鎖,它工作正常。但是,當我明確地將手機置於深度睡眠模式時,處理程序將停止執行。我在哪裏放置喚醒服務。下面的代碼片段。喚醒鎖定android服務定期發送

public class PlaySound extends Service{ 
PowerManager.WakeLock wl ; 
    PowerManager pm; 
private SoundManager mSoundManager; 
    boolean wakeUpFlag = false; 

@Override 
    public void onCreate(){ 
     super.onCreate(); 
     mSoundManager = new SoundManager(); 
     mSoundManager.initSounds(getBaseContext()); 
     mSoundManager.addSound(1, R.raw.sound); 
    } 
@Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     startservice(); 
     return START_STICKY; 
    } 
private void startservice() { 
     System.out.println("Started the service"); 
     timer.scheduleAtFixedRate(new TimerTask() { 
      public void run() { 
       toastHandler.sendEmptyMessage(0); 
      } 
     }, 0, 60000); 
    } 
private final Handler toastHandler = new Handler() 
    { 
     @Override 
     public void handleMessage(Message msg) 
     { 
      result =start(); 

       System.out.println("result"+result); 
       close(); 
     } 
    }; 

protected void close() { 
     try { 
      if(wakeUpFlag){ 
       wl.release(); 
       System.out.println("Released the wakelock"); 
      } 

      if(!pm.isScreenOn()){ 
       System.out.println("Screen is off - back to sleep"); 
       pm.goToSleep(1000); 
      } 
      else{ 
       System.out.println("Screen is on - no need to sleep"); 
      } 
      bs.close(); 
      writer.close(); 
      System.out.println("Closed socket and writer"); 
      System.out.println("Size of file:"+f.length()/1024); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
public void start(){ 
     try{ 
      wakeUpFlag = false; 
      pm = (PowerManager)getSystemService(Context.POWER_SERVICE); 


      if(!pm.isScreenOn()) { 
       wakeUpFlag = true; 
       wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,"CollectData"); 
       System.out.println("Screen off - wake lock acquired"); 
       wl.acquire(); 
      } 
      else{ 
       System.out.println("Screen on - no need of wake lock"); 
      } 



     } 
     catch(Exception e){ 
      e.printStackTrace(); 
     } 
mSoundManager.playSound(1); 
} 

回答

3

按照模式馬克墨菲提供的WakefulIntentService。我建議你拿起自己的書,不僅是爲了詳細解釋這門課的內容,還有他在其中的一個例子中所包含的例子,以及其他你可以在其中找到的大量信息。

我剛剛爲我的主應用程序實現了這個模式,這個類就像一個魅力。

+0

。已經訂閱了他的書..我必須說..他們很棒!謝謝 – 2011-03-22 04:57:01

4

我不認爲你使用了正確的標誌accorinding到Android文檔FIOR PowerManager

*如果您持有部分激活鎖定,CPU將繼續後運行,不論任何計時器,甚至用戶按下電源按鈕。在所有其他喚醒鎖中,CPU將運行,但用戶仍然可以使用電源按鈕使設備進入睡眠狀態。

換句話說,嘗試使用PARTIAL_WAKE_LOCK因爲這是註冊就CPU的運行

1

我想你會更好使用android.app.AlarmManager安排喚醒報警唯一的一個。不過要小心 - 你不想在你的onReceive()方法中執行任何長時間運行的工作,就像在主線程中通常調用的那樣,並且會掛起你的活動。在任務期間,您仍然需要獲取喚醒鎖以防止手機部分通過。