Reputation: 73
Hi I'm new to Android. I want to notify the user everyday at a certain time. I tried to use AlarmManager fires up a Service, in this Service I set up a notification. My codes are below and they are not working right now:
My alarm service code:
public class MyAlarmService extends Service
{
private NotificationManager mManager;
@Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
@SuppressWarnings("static-access")
@Override
public void onStart(Intent intent, int startId)
{
Intent intents = new Intent(getBaseContext(), MainActivity.class);
intents.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent m_PendingIntent = PendingIntent.getActivity(
getBaseContext(), 0, intents, PendingIntent.FLAG_UPDATE_CURRENT);
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setDefaults(Notification.DEFAULT_SOUND
| Notification.DEFAULT_VIBRATE);
mBuilder.setContentIntent(m_PendingIntent);
mManager.notify(0, mBuilder.build());
}
@Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
My receiver code:
public class MyReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Intent service1 = new Intent(context, MyAlarmService.class);
context.startService(service1);
}
}
code in MainActivity:
Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), 1000 * 60 * 60 * 24, pendingIntent);
Right now, the notification will not show up after I set the time. Where is my problem?
Upvotes: 0
Views: 340
Reputation: 8023
You should override the onStartCommand()
method in your Service in place of onStart()
. The onStart()
method is called only on pre Android 2.0 Platforms. On the later versions of Android, only the onStartCommand()
is called.
Upvotes: 1