Skip to content

Instantly share code, notes, and snippets.

@moea
Created January 20, 2016 11:50
Show Gist options
  • Save moea/3f35b7d44ad7c1a56832 to your computer and use it in GitHub Desktop.
Save moea/3f35b7d44ad7c1a56832 to your computer and use it in GitHub Desktop.
package io.nervous.alarmtest;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.widget.Toast;
public class AlarmIntentService extends IntentService {
public AlarmIntentService() {
super("AlarmIntentService");
}
Uri alertUri() {
Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if(alert == null) {
alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if(alert == null) {
alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
}
}
return alert;
}
void notification(String text) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_template_icon_bg)
.setContentTitle("AlarmTest")
.setContentText(text);
Intent resultIntent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, mBuilder.build());
}
@Override
protected void onHandleIntent(Intent intent) {
SharedPreferences prefs = getSharedPreferences(getPackageName(), Context.MODE_PRIVATE);
long expected = prefs.getLong("expected", -1);
String desc = "Alarm was " + (System.currentTimeMillis() - expected) + " milliseconds early";
Toast.makeText(this, desc, Toast.LENGTH_LONG).show();
notification(desc);
Ringtone ringtone = RingtoneManager.getRingtone(this, alertUri());
ringtone.play();
Intent activityIntent = new Intent(this, MainActivity.class);
activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(activityIntent);
try {
Thread.sleep(5 * 1000);
} catch(InterruptedException e) {}
ringtone.stop();
AlarmWakefulReceiver.completeWakefulIntent(intent);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment