I have the following code to trigger an alarm, which when it fires is meant to launch another activity that is basically a nap alarm. After much searching through Google and SO, I am at a loss. I believe I have the correct setup for the AlarmManager, but the Activity that it is supposed to launch never gets launched.
By the way, eventually I want to use the napTime variable to set the time at which the AlarmManager will fire, but for testing purposes I am just trying to get it to fire right way.
Here is the code to set the nap. The Log.e("Nap time", "" + napTime); line always shows the correct number that was selected for the napTime, so I know that the method is executing.
private void setNap(int napTime) {
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(getApplicationContext(), NapAlarm.class);
// i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0, i, 0);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pi);
Log.e("Nap time", "" + napTime);
TextView nap = (TextView) findViewById(R.id.nap);
nap.setText("nap set");
}
And the code for the activity that is launched:
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
public class NapAlarm extends Activity implements OnClickListener {
MediaPlayer mp;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alarm_layout);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
Button dButton = (Button) findViewById(R.id.dismissButton);
dButton.setOnClickListener(this);
Button sButton = (Button) findViewById(R.id.snoozeButton);
sButton.setOnClickListener(this);
new Thread(new Runnable() {
public void run() {
try {
Log.e("Got this far", "In the alarm");
mp = MediaPlayer.create(getApplicationContext(), R.raw.alarm);
mp.start();
mp.setLooping(true);
} catch (Exception e) {
}
}
}).start();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.dismissButton:
mp.stop();
this.finish();
break;
case R.id.snoozeButton:
Button sButton = (Button) findViewById(R.id.snoozeButton);
sButton.setText("I'm sorry, this app currently does not support snoozing, you must wake up.");
break;
}
}
}
If I run the second piece of code by itself, it works and the sound plays, etc. But if I run it from within the larger project from which the AlarmMananger is supposed to create an alarm to trigger it, it never happens.
Is there something that I am overlooking?
Your NapTime activity should be extending a BroadCast Receiver like this..
Make sure you register your reciever like this..
Refer here for more info
Alarm Manager tutorial