Friday, 14 June 2013

Android: Notification for certain time using AlaramManager


AlarmService.java

public class AlarmService extends Activity {

AlarmManager am;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
setOneTimeAlarm();
}

public void setOneTimeAlarm() {

Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_ONE_SHOT);
am.set(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + (1 * 5000), pendingIntent);
}
//
// public void setRepeatingAlarm() {
// Intent intent = new Intent(this, AlarmReceiver.class);
// PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
// intent, PendingIntent.FLAG_CANCEL_CURRENT);
// am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
// (1 * 1000), pendingIntent);
// }

}

AlarmReceiver.java


public class AlarmReceiver extends BroadcastReceiver {

NotificationManager nm;

@Override
public void onReceive(Context context, Intent intent) {

intent = new Intent(context, AlarmService.class);
nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence from = "Title";
CharSequence message = "Description...";
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
intent, 0);
Notification notif = new Notification(R.drawable.ic_launcher,
"Message...", System.currentTimeMillis());
notif.setLatestEventInfo(context, from, message, contentIntent);
nm.notify(1, notif);
}
}

Manifest


 <receiver
            android:name="com.example.alarmmanager.AlarmReceiver"
            android:process=":remote" >
        </receiver>



No comments:

Post a Comment