问题
I have to create an app in which I must set a date and at that specific date at 9 O'clock, I must give a notification. What is the simplest method of doing this? I want the app to work even when the app gets killed anyway. Is AlarmManager a solution?
回答1:
To schedule an Action you can use the AlarmManager
Try this code it's work for me:
1 / Declare the BroadcastReceiver CLASS to launch the Action, this class can be inside your activity or outside in an other java file
public class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(context, intent.getStringExtra("param"),Toast.LENGTH_SHORT).show();
}
}
2/ Inside your Oncreate Method put this code
AlarmManager alarms = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
Receiver receiver = new Receiver();
IntentFilter filter = new IntentFilter("ALARM_ACTION");
registerReceiver(receiver, filter);
Intent intent = new Intent("ALARM_ACTION");
intent.putExtra("param", "My scheduled action");
PendingIntent operation = PendingIntent.getBroadcast(this, 0, intent, 0);
// I choose 3s after the launch of my application
alarms.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+3000, operation) ;
Launch your App a Toast will be appeared after 3 seconds, So you can change "System.currentTimeMillis()+3000" with your wake up time.
回答2:
You must use an AlarmManager
to set an alarm of RTC_WAKEUP type.
From the docs:
When an alarm goes off, the Intent that had been registered for it is broadcast by the system, automatically starting the target application if it is not already running. Registered alarms are retained while the device is asleep (and can optionally wake the device up if they go off during that time), but will be cleared if it is turned off and rebooted.
So this means that:
- You don't need a continually running service to achieve this.
- To may need a
BroadcastListener
that listens to the BOOT_COMPLETE event to re-register the alarm after a device reboot.
回答3:
You should create the app as an android service.
A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.
回答4:
Alarm manager is the solution i guess. you should set the alarm manager to a specific time and then make it call the notification in its onstart. and this should be implemented within a service. i hope it helped.
来源:https://stackoverflow.com/questions/9930683/android-notification-at-specific-date