2011-09-07 56 views
1

我正在尋找一種方法來讓我的程序在屏幕從超時關閉後使手機振動。我做了大量的研究,並沒有找到可行的方法。我看過PowerManager類,更具體地說是WakeLock機制。從許多帖子的聲音中,我需要使用WakeLock類的PARTIAL_WAKE_LOCK變量。允許手機在屏幕關閉時振動

PARTIAL_WAKE_LOCK - 喚醒鎖確保CPU正在運行。

但是,我不能讓它在屏幕關閉時振動手機。我知道我正在使用WakeLock,因爲我可以讓SCREEN_DIM_WAKE_LOCK工作。 PARTIAL_WAKE_LOCK是我在找什麼?

回答

4
@Override 

    public void onCreate() { 

     super.onCreate(); 

     // REGISTER RECEIVER THAT HANDLES SCREEN ON AND SCREEN OFF LOGIC 

     IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON); 

     filter.addAction(Intent.ACTION_SCREEN_OFF); 

     BroadcastReceiver mReceiver = new ScreenReceiver(); 

     registerReceiver(mReceiver, filter); 

    } 



    @Override 

    public void onStart(Intent intent, int startId) { 

     boolean screenOn = intent.getBooleanExtra("screen_state", false); 

     if (!screenOn) { 

      // Get instance of Vibrator from current Context 
      Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); 
      // This example will cause the phone to vibrate "SOS" in Morse Code 
      // In Morse Code, "s" = "dot-dot-dot", "o" = "dash-dash-dash" 
      // There are pauses to separate dots/dashes, letters, and words 
      // The following numbers represent millisecond lengths 
      int dot = 200;  // Length of a Morse Code "dot" in milliseconds 
      int dash = 500;  // Length of a Morse Code "dash" in milliseconds 
      int short_gap = 200; // Length of Gap Between dots/dashes 
      int medium_gap = 500; // Length of Gap Between Letters 
      int long_gap = 1000; // Length of Gap Between Words 
      long[] pattern = { 
      0, // Start immediately 
      dot, short_gap, dot, short_gap, dot, // s 
      medium_gap, 
      dash, short_gap, dash, short_gap, dash, // o 
      medium_gap, 
      dot, short_gap, dot, short_gap, dot, // s 
      long_gap 
      }; 

      // Only perform this pattern one time (-1 means "do not repeat") 
      v.vibrate(pattern, -1); 


     } else { 

      // YOUR CODE 

     } 

    } 

請注意您必須將用戶權限行添加到塊的外部的Manifest.xml文件中。

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="..."> 
<uses-permission android:name="android.permission.VIBRATE"/> 

注意:您還必須測試此代碼真正的手機上,仿真器將無法viberate

+0

+1 fot「模擬器無法振動」:-) – Twinone

+0

請在沒有USB電纜連接到設備的情況下測試,因爲充電時行爲會有所不同。 – userM1433372

1

對我來說,解決辦法是直接使用無需振動模式,所以我沒有使用電源管理器喚醒鎖定。

+0

你說得對。這很好。謝謝 – Snicolas