Reputation: 1121
I use the following code for setting repeating events in AlarmManager
:
mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
PERIOD, getPendingIntent(time));
Code for receiver:
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();
}
}
There is some problem - I need to play music when the event happens, but if my device is in sleeping I don't hear any signal! But when I wake up device I hear music. How can I fix it?
Upvotes: 2
Views: 715
Reputation: 3373
When i have to do this, I create the following class:
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;
}
}
Then you can call WakeLocker.acquire(getApplicationContext());
to wake up your phone, but don't forget to call WakeLocker.release();
when your action is finished.
Also, add the following permission to your manifest: <uses-permission android:name="android.permission.WAKE_LOCK" />
Hope this help.
Upvotes: 1