特定日期的Android通知

Buz*_*uze 9 android alarmmanager android-notifications android-date

我必须创建一个应用程序,我必须在其中设置日期,在特定日期9点钟,我必须发出通知.这样做最简单的方法是什么?即使应用程序被杀,我希望应用程序能够正常运行.AlarmManager是一个解决方案吗?

小智 15

要安排操作,您可以使用AlarmManager

试试这个代码它对我有用:

1 /声明BroadcastReceiver CLASS启动Action,这个类可以在你的活动里面或在其他java文件外面

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();
    }

}
Run Code Online (Sandbox Code Playgroud)

2 /在你的Oncreate方法里面放了这个代码

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) ;   
Run Code Online (Sandbox Code Playgroud)

启动你的应用程序将在3秒后出现Toast,因此您可以在唤醒时更改"System.currentTimeMillis()+ 3000".