java如何在Android上使用AlarmManager在所需日期显示Toast
在我的应用程序中,我希望在所需日期中显示吐司。为此,我知道我应该使用AlarmManager
对于这个AlarmManager
,我从互联网上找到了源代码
在这个源代码中,使用时间选择器从用户那里获得时间,但我希望获得时间静态
我想在下面的日期显示吐司:
日期:2017年10月26日
时间:06:49:59
main活动代码:
public class MainActivity extends AppCompatActivity {
//the timepicker object
TimePicker timePicker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//getting the timepicker object
timePicker = (TimePicker) findViewById(R.id.timePicker);
//attaching clicklistener on button
findViewById(R.id.buttonAlarm).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//We need a calendar object to get the specified time in millis
//as the alarm manager method takes time in millis to setup the alarm
Calendar calendar = Calendar.getInstance();
if (安卓.os.Build.VERSION.SDK_INT >= 23) {
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH),
timePicker.getHour(), timePicker.getMinute(), 0);
} else {
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH),
timePicker.getCurrentHour(), timePicker.getCurrentMinute(), 0);
}
setAlarm(calendar.getTimeInMillis());
}
});
}
private void setAlarm(long time) {
//getting the alarm manager
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//creating a new intent specifying the broadcast receiver
Intent i = new Intent(this, MyAlarm.class);
//creating a pending intent using the intent
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
//setting the repeating alarm that will be fired every day
am.setRepeating(AlarmManager.RTC, time, AlarmManager.INTERVAL_DAY, pi);
Toast.makeText(this, "Alarm is set", Toast.LENGTH_SHORT).show();
}
}
广播代码:
public class MyAlarm extends BroadcastReceiver {
//the method will be fired when the alarm is triggerred
@Override
public void onReceive(Context context, Intent intent) {
//you can check the log that it is fired
//Here we are actually not doing anything
//but you can do any task here that you want to be done at a specific time everyday
Toast.makeText(context, "Alarm just fired", Toast.LENGTH_SHORT).show();
}
}
我该怎么做?我是业余爱好者,请帮帮我<;三,
# 1 楼答案
见GregorianCalendar
# 2 楼答案
试试这段代码
# 3 楼答案
根据您的选择创建一个日期,并将其传递给方法setAlarm()