2013-03-28 128 views
2

我用下面的代碼來設置重複事件AlarmManager如何使用鬧鐘喚醒設備?

mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 
    PERIOD, getPendingIntent(time)); 

代碼接收器:

public class NotificationsReceiver extends BroadcastReceiver { 
    public static final String NOTIFICATION_INFO="notification_info"; 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     playSound(context); 
     Intent i=new Intent(context, MainActivity.class); 
     i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     context.startActivity(i); 
    } 

    private void playSound(Context context) { 
     Uri notification=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
     RingtoneManager.getRingtone(context, notification).play(); 
    } 
} 

有一些問題 - 我需要當事件發生時播放音樂,但如果我的設備在睡覺我沒有聽到任何信號!但是當我喚醒設備時,我會聽到音樂。我該如何解決它?

回答

1

當我不得不這樣做,我創建了以下類:

import android.content.Context; 
import android.os.PowerManager; 

public abstract class WakeLocker { 
    private static PowerManager.WakeLock wakeLock; 

    public static void acquire(Context context) { 
     if (wakeLock != null) wakeLock.release(); 

     PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); 
     wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | 
       PowerManager.ACQUIRE_CAUSES_WAKEUP | 
       PowerManager.ON_AFTER_RELEASE, "WakeLock"); 
     wakeLock.acquire(); 
    } 

    public static void release() { 
     if (wakeLock != null) wakeLock.release(); wakeLock = null; 
    } 
} 

然後就可以調用WakeLocker.acquire(getApplicationContext());來喚醒你的手機,但不要忘記調用WakeLocker.release();當你的動作完成。

此外,添加以下權限到你的清單:<uses-permission android:name="android.permission.WAKE_LOCK" />

希望這有助於。