Android : how to set the calendar alert in android - android

Is it possible to show calendar alert in android, so that on the specified date the alert should pop up and remind the user regarding the task.

Sorry, there isn't currently a calendar API in the SDK. You can however implement your own alarm with the AlarmManager showing your own UI at the time you schedule with it.

first of all to set the alert in calendar application you have to make the permit-ion :
Now, that the alarm receiver is set, lets take a look at the class that will set and cancel the alarms:
package SomeApp.SomeApp;
import java.util.Calendar;
import java.lang.String;
import android.app.AlarmManager;
import android.app.ListActivity;
import android.app.PendingIntent;
import android.os.Bundle;
import android.util.Log;
import android.content.Intent;
import android.widget.Toast;
/**
* When this code is run only one alert will be displayed even though 2 alerts were
* were setup (as one of them will be cancelled later on
*/
public class SomeApp extends ListActivity {
/* for logging - see my tutorial on debuggin Android apps for more detail */
private static final String TAG = "SomeApp ";
protected Toast mToast;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.alert_list);
try {
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(SomeApp.this, AReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 1234567, intent, 0);
PendingIntent sende2 = PendingIntent.getBroadcast(this, 123123, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis()+30000, sender); // to be alerted 30 seconds from now
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis()+15000, sende2); // to be alerted 15 seconds from now
/* To show how alarms are cancelled we will create a new Intent and a new PendingIntent with the
* same requestCode as the PendingIntent alarm we want to cancel. In this case, it is 1234567.
* Note: The intent and PendingIntent have to be the same as the ones used to create the alarms.
*/
Intent intent1 = new Intent(SomeApp.this, AReceiver.class);
PendingIntent sender1 = PendingIntent.getBroadcast(this, 1234567, intent1, 0);
AlarmManager am1 = (AlarmManager) getSystemService(ALARM_SERVICE);
am1.cancel(sender1);
} catch (Exception e) {
Log.e(TAG, "ERROR IN CODE:"+e.toString());
}
}
}
You will notice that this is only a "one-shot" alarm. If you want to set a repeating alarm, it is explained in Android's documentation. However, I will write on that too if there is demand for it. Now, let's examine the code. For setting an alarm, you will need 4 things:
The class that's setting the alarm
The class that will be called when the alarm "goes off"
The time at which the alarm should go off
A requestCode (which will use as a unique ID to identify the alarms) used in PendingIntent.
For cancelling an alarm, you need 3 things:
The class that set the alarm
The class that was to be called when the alarm "goes off"
The requestCode you used for PendingIntent object.
We have covered 2 things - the declaration of the receiver in our manifest file and the class that sets and cancels alarms. Now, we need to look at the class that will be called when the alarm goes off.
package someApp.someApp;
import java.util.Calendar;
import android.content.Context;
import android.content.BroadcastReceiver;
import android.util.Log;
import android.widget.Toast;
/** All receiver classes must extend BroadcastReceiver */
public class AReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context con, Intent in) {
try {
/* Display an alert */
Toast.makeText(con, "hello my jello ", Toast.LENGTH_LONG).show();
} catch (Exception r) {
Toast.makeText(con, "You were supposed to do something"
+" now but I can't retrieve what it was.",
Toast.LENGTH_SHORT).show();
Log.e("ALARM_RECEIVER", r.toString());
}
}
}

AND YOU are able to use this other ans also...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, 0);
cal.set(Calendar.HOUR_OF_DAY, 9);
cal.set(Calendar.MINUTE, 01);
cal.set(Calendar.SECOND, 0);
setAlarm(cal);
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 30);
setAlarm(cal);
//etc
}
public void setAlarm(Calendar cal) {
try {
Intent intent = new Intent(Alarm.this, Alarm1.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 1234567, intent, 0);
PendingIntent sende2 = PendingIntent.getBroadcast(this, 123123, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender); // to be alerted 30 seconds from now
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sende2); // to be alerted 15 seconds from now
/* To show how alarms are cancelled we will create a new Intent and a new PendingIntent with the
* same requestCode as the PendingIntent alarm we want to cancel. In this case, it is 1234567.
* Note: The intent and PendingIntent have to be the same as the ones used to create the alarms.
*/
Intent intent1 = new Intent(Alarm.this, Alarm1.class);
PendingIntent sender1 = PendingIntent.getBroadcast(this, 1234567, intent1, 0);
AlarmManager am1 = (AlarmManager) getSystemService(ALARM_SERVICE);
am1.cancel(sender1);
} catch (Exception e) {
Log.e(TAG, "ERROR IN CODE:"+e.toString());
}
}

Related

Android app with daily notification

I'm making an android application.... and I've been trying to write the code for a daily notification set for a specific time of day. At first, I really thought this would be an easy task, almost every app in the play store has a timed notification. But after searching over and over again, all the methods and Youtube tutorials I've found failed to work for me. The problem probably lies in me, but I don't know what it is. All I need is a simple, elegant, easy to understand method (if there is such a thing). Any help would be greatly appreciated.
All the searching I've done has gotten me this far... but still without any luck:
This method is in my MainActivity class and is called only the first time the app is launched to set the alarm...
private void alarmMethod() {
Intent myIntent = new Intent(this, NotifyService.class);
AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
// Set the alarm to start at approximately 2:00 p.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 14);
// With setInexactRepeating(), you have to use one of the AlarmManager interval
// constants--in this case, AlarmManager.INTERVAL_DAY.
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
Toast.makeText(MainActivity.this, "Start Alarm", Toast.LENGTH_LONG)
.show();
This is my NotifyService class:
package com.OHS.example;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
public class NotifyService extends Service {
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationManager mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(), MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent1, 0);
Notification mNotify = new NotificationCompat.Builder(this)
.setContentTitle("Title")
.setContentText("Hello World!")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent)
.setSound(sound)
.build();
mNM.notify(1, mNotify);
}
}
Try This Code.
XML layout :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/TextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android Alarm Example:\n\rSetup an alarm event after 10 seconds from the current time. So just press Setup Alarm button and wait for 10 seconds. You can see a toast message when your alarm time will be reach." />
<Button
android:id="#+id/setAlarm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/TextView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:onClick="onClickSetAlarm"
android:text="Set Alarm" />
Main Activity :
public class MainActivity extends Activity {
//used for register alarm manager
PendingIntent pendingIntent;
//used to store running alarmmanager instance
AlarmManager alarmManager;
//Callback function for Alarmmanager event
BroadcastReceiver mReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Register AlarmManager Broadcast receive.
RegisterAlarmBroadcast();
}
public void onClickSetAlarm(View v)
{
//Get the current time and set alarm after 10 seconds from current time
// so here we get
alarmManager.set( AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 10000 , pendingIntent );
}
private void RegisterAlarmBroadcast()
{
Log.i("Alarm Example:RegisterAlarmBroadcast()", "Going to register Intent.RegisterAlramBroadcast");
//This is the call back function(BroadcastReceiver) which will be call when your
//alarm time will reached.
mReceiver = new BroadcastReceiver()
{
private static final String TAG = "Alarm Example Receiver";
#Override
public void onReceive(Context context, Intent intent)
{
Log.i(TAG,"BroadcastReceiver::OnReceive() >>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
Toast.makeText(context, "Congrats!. Your Alarm time has been reached", Toast.LENGTH_LONG).show();
}
};
// register the alarm broadcast here
registerReceiver(mReceiver, new IntentFilter("com.myalarm.alarmexample") );
pendingIntent = PendingIntent.getBroadcast( this, 0, new Intent("com.myalarm.alarmexample"),0 );
alarmManager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
}
private void UnregisterAlarmBroadcast()
{
alarmManager.cancel(pendingIntent);
getBaseContext().unregisterReceiver(mReceiver);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
}
I Hope this will help you, this worked for me.
You can always calculate and set the time when you want to trigger the alarm.
Happy Coding !!
You could use AlarmManager to schedule the daily notification. The document here provide a good explanation and example.
Setup the alarm.
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(this, 0,
new Intent(this, MainService.class),
PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
// set the triggered time to currentHour:08:00 for testing
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 8);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 0, pendingIntent);
Service to handle the alarm.
public class MainService extends IntentService {
public MainService() {
super("mainservice");
}
public MainService(String name) {
super(name);
}
/*
* (non-Javadoc)
*
* #see android.app.IntentService#onHandleIntent(android.content.Intent)
*/
#Override
protected void onHandleIntent(Intent intent) {
showNotification();
}
private void showNotification() {
Uri soundUri = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("Alarm title")
.setContentText("Alarm text")
.setContentIntent(
PendingIntent.getActivity(this, 0, new Intent(this,
SecondActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT))
.setSound(soundUri).setSmallIcon(R.drawable.ic_launcher)
.build();
NotificationManagerCompat.from(this).notify(0, notification);
}
}
as alijandro said if you want to have a daily notification in specific time you could use AlarmManager to schedule it and at that time show notification or if you want to get data from server, send a http request to retrieve your data and show notification to the user.
But if you want to have push notification anytime you want, you could use GCM (Google Cloud Messaging). Look at this doc.

Why the alarm receiver is not trigger in android?

I am implement a simple alarm function, which is used to trigger some function at the specific date time.
The problem is I have set the time already, but the receiver seems never called.
Here is how I implement:......
1) in manifest :
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
and
<receiver android:name=".Listener.AlarmReceiver" />
2) in the main activity (I would like to trigger on 4th June 2014, 02:06 p.m.)
profilePic.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
GregorianCalendar date = new GregorianCalendar(2014,6,4,14,6);
long dateTime = date.getTimeInMillis();
Log.d("test1",date.toString());
AlarmManager alarmManager = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
Intent intentAlarm = new Intent(ctx, AlarmReceiver.class);
alarmManager.set(AlarmManager.RTC_WAKEUP, dateTime, PendingIntent.getBroadcast(ctx, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
}
});
And I have also log the time
java.util.GregorianCalendar[time=1404453960000,areFieldsSet=true,lenient=true,zone=Asia/Hong_Kong,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2014,MONTH=6,WEEK_OF_YEAR=27,WEEK_OF_MONTH=1,DAY_OF_MONTH=4,DAY_OF_YEAR=185,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=1,AM_PM=1,HOUR=2,HOUR_OF_DAY=14,MINUTE=6,SECOND=0,MILLISECOND=0,ZONE_OFFSET=28800000,DST_OFFSET=0]
3) Receiver
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("test1", "alarm");
Toast.makeText(context, "Alarm Triggered", Toast.LENGTH_LONG).show();
}
}
I waited until the 02:06p.m. but nothing happened, and receiver is not called. How to fix the problem? Also, is it possible to set more than one alarm, is it all I need to do is to create another datetime and fire the alarmManager.set() again, will it overwrite the old timer? Thanks for helping.
Updated
For the AlarmReceiver in the mainifest ,
I changed to
<receiver android:name="com.example.antismoke.Listener.AlarmReceiver" />
And the class is
package com.example.antismoke.Listener;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("test1", "alarm");
Toast.makeText(context, "Alarm Triggered", Toast.LENGTH_LONG).show();
}
}
so I think package name is not the root cause? Thanks for helping
Instead of using GregorianCalendar , try to use Calendar.
Try the following, it should work:
Intent i = new Intent(getApplicationContext(), AlarmReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(AlarmSample.this, 0, i, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour); // set hour
calendar.set(Calendar.MINUTE, minuite); // set minute
calendar.set(Calendar.SECOND, 0); // set seconds
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
you should use package name correctly, if you have different package ,
receiver android:name="XXX.XXXXXXXXXXXXXXX.AlarmReceiver" />
check this out
1) You don't need this persmission (com.android.alarm.permission.SET_ALARM) to receive alarm.
2) Change this line:
<receiver android:name=".Listener.AlarmReceiver" />
to
<receiver android:name=".AlarmReceiver" />
replace alarmManager.set with alarmManager.setRepeating
or try to use this:
public static AlarmManager am = null;
public static PendingIntent sender;
Intent intent1 = new Intent(ctx, Reciver.class);
sender = PendingIntent.getBroadcast(ctx, 1, intent1, 0);
am = (AlarmManager) getSystemService(ALARM_SERVICE);
long l = new Date().getTime();
am.setRepeating(AlarmManager.RTC_WAKEUP, l, 1500, sender);
Ok , finally I figure out it is because the month start at 0 in GregorianCalendar. So June should use 5 instead of 6
I should have noticed the problem. Thanks for all you guys

How to stop service at particular time on Android?

Start my service at : 8am. I don't know how to stop service at specific time.
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, MyService.class);
PendingIntent pi = PendingIntent.getService(this,
(int) System.currentTimeMillis(), intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000, pi);
I want Myservice start at 8am and stop at 6pm in everyday.
Please help me. Thanks.
you could use the AlarmManager, .cancel(PendingIntent intent) at the myService.class, checking whether it's 6pm and cancel the alarm if the intent exists.
Check the API:
Alarm Manager API
This might be an old question but I came across this issue myself today and figured a way to do it:
You can use a new service which stops your service, and start that service in the desired time on a daily basis using alarm manager, like this:
Define the service which will stop your service:
package com.youractivity;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class MyServiceTerminator extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_NOT_STICKY;
}
public void onCreate()
{
Intent service = new Intent(this, MyService.class);
stopService(service); //stop MyService
stopSelf(); //stop MyServiceTerminator so that it doesn't keep running uselessly
}
#Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
}
add the following code after the one you posted, and run the method inside your activity:
private void stopRecurringAlarm(Context context) {
Calendar updateTime = Calendar.getInstance();
updateTime.setTimeZone(TimeZone.getTimeZone("GMT+3"));
updateTime.set(Calendar.HOUR_OF_DAY, 18);
updateTime.set(Calendar.MINUTE, 0);
Intent intent = new Intent(this, MyServiceTerminator.class);
PendingIntent pintent = PendingIntent.getService(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarms.setRepeating(AlarmManager.RTC_WAKEUP,updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pintent);
}
this way the service will be scheduled to start as you posted above, and scheduled to stop at 6 as shown in the code I posted.
You can use AlarmManager for scheduling and cancel method to stop.
alarmMgr.cancel(alarmIntent);
you can find all your necessary information here
https://developer.android.com/training/scheduling/alarms.html

Android AlarmManager after reboot

I have a set of alarms that I need to keep after reboot. I've tried using on an boot receiver but they won't start again. I'm not sure if I understand the boot receiver and how to then restart all the alarms. I already have one receiver for my notifications, but don't know whether I can use the same receiver or if I need a new one?
Could anyone point me to any good tutorials or help me out?
Cheers
Code :
DatabaseHandler db = new DatabaseHandler(this);
List<UAlarm> alarms = db.getAllAlarms();
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
for (UAlarm ua : alarms) {
String programme = ua.getTitle();
String startTime = ua.getStart();
String endTime = ua.getEnd();
String nowPlaying = ua.getChannel();
db.addAlarm(new UAlarm(programme, startTime, endTime, nowPlaying, ""));
final UAlarm ut = new UAlarm();
ut.setTitle(programme);
ut.setStart(startTime);
ut.setEnd(endTime);
ut.setChannel(nowPlaying);
ut.setId(db.getLastEntered());
String [] bla = startTime.split(":");
int hour = Integer.parseInt(bla[0].trim());
int minute = Integer.parseInt(bla[1].trim());
minute -= 2;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
Intent intenta = new Intent(this, NotificationMenu.class);
String name = programme;
intenta.putExtra("name", name);
intenta.putExtra("id", db.getLastEntered());
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, ua.getId(),
intenta, PendingIntent.FLAG_CANCEL_CURRENT);
am.set(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), pendingIntent);
}
}
with NotificationMenu being the notifications, which is why I'm using the AlarmManager
I'm not sure if I understand the boot receiver and how to then restart all the alarms.
Just call your code to call setRepeating() (or whatever) on AlarmManager.
For example, in this sample project, PollReceiver is set to receive BOOT_COMPLETED. In onReceive(), it reschedules the alarms:
package com.commonsware.android.schedsvc;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
public class PollReceiver extends BroadcastReceiver {
private static final int PERIOD=5000;
#Override
public void onReceive(Context ctxt, Intent i) {
scheduleAlarms(ctxt);
}
static void scheduleAlarms(Context ctxt) {
AlarmManager mgr=
(AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(ctxt, ScheduledService.class);
PendingIntent pi=PendingIntent.getService(ctxt, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + PERIOD, PERIOD, pi);
}
}

How to start an activity using AlarmManager etc

I am trying to start code inside an activity at regular intervals using Alarm manager. I have looked at various examples on here but they have not really helped.
For testing purposes, all I am trying to do is pop up a toast at 10 second intervals, but nothing seems to be happening at all. Please help guys!
I have this in the manifest (also declarations for all three activities):
<receiver android:name=".receiver.AlarmReceiver"></receiver>
Code from main activity, in OnCreate:
//
// Setting up the Alarm Manager
//
Intent myIntent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
long timerInterval = 10 * 1000;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), timerInterval, pendingIntent);
//finish();
AlarmReceiver.java:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context," onRecieve() test" , Toast.LENGTH_LONG).show();
Intent scheduledIntent = new Intent(context, MyService.class);
scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(scheduledIntent);
}
}
MyService.java:
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
public void onCreate(Bundle savedInstanceState) {
super.onCreate();
Toast.makeText(getBaseContext(),"test message.",
Toast.LENGTH_SHORT).show();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
Your activity is not showing, because you are calling startActivity() on an Intent that identifies a Service. You should see warnings related to this in LogCat.
I humbly suggest that you use LogCat yourself, via the Log class, for logging background operations, rather than attempting to use a Toast.
test this code:
private void establecerAlarmaClick(int when){
AlarmManager manager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(MainActivityAlarmita.this, MainActivityAlarmita.class);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivityAlarmita.this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
((AlarmManager) getSystemService(ALARM_SERVICE)).set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + when * 1000, pendingIntent);
}

Categories

Resources