设置特定日期和时间的通知[关闭]
Posted
技术标签:
【中文标题】设置特定日期和时间的通知[关闭]【英文标题】:Set notification for specific date and time [closed] 【发布时间】:2016-01-04 00:35:28 【问题描述】:如何在不使用服务的情况下在android studio中创建特定日期和时间的通知?
【问题讨论】:
欢迎堆栈溢出!有关如何在此处提问的一些提示,请参阅***.com/help/on-topic。您是否遇到了特定问题?你能分享一些你现在拥有的代码吗? 【参考方案1】:使用在后台运行代码的类 AlarmManager。将此代码放在主Activity中:
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.your layout);
boolean alarm = (PendingIntent.getBroadcast(this, 0, new Intent("ALARM"), PendingIntent.FLAG_NO_CREATE) == null);
if(alarm)
Intent itAlarm = new Intent("ALARM");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,itAlarm,0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 3);
AlarmManager alarme = (AlarmManager) getSystemService(ALARM_SERVICE);
alarme.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),60000, pendingIntent);
创建一个新类来控制是否在通知时间。
public class BroadcastManager extends BroadcastReceiver
@Override
public void onReceive(Context context, Intent intent)
try
String yourDate = "04/01/2016";
String yourHour = "16:45:23";
Date d = new Date();
DateFormat date = new SimpleDateFormat("dd/MM/yyyy");
DateFormat hour = new SimpleDateFormat("HH:mm:ss");
if (date.equals(yourDate) && hour.equals(yourHour))
Intent it = new Intent(context, MainActivity.class);
createNotification(context, it, "new mensage", "body!", "this is a mensage");
catch (Exception e)
Log.i("date","error == "+e.getMessage());
public void createNotification(Context context, Intent intent, CharSequence ticker, CharSequence title, CharSequence descricao)
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent p = PendingIntent.getActivity(context, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setTicker(ticker);
builder.setContentTitle(title);
builder.setContentText(descricao);
builder.setSmallIcon(R.drawable.yourIcon);
builder.setContentIntent(p);
Notification n = builder.build();
//create the notification
n.vibrate = new long[]150, 300, 150, 400;
n.flags = Notification.FLAG_AUTO_CANCEL;
nm.notify(R.drawable.yourIcon, n);
//create a vibration
try
Uri som = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone toque = RingtoneManager.getRingtone(context, som);
toque.play();
catch(Exception e)
在清单中放这个:
<receiver
android:name="BroadcastManager"
android:label="BroadcastReceiverAux">
<intent-filter>
<action android:name="ALARM" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
授予此权限:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"
【讨论】:
它在 Marshmallow 上完美运行,但在 android 10 上无法运行。任何解决方案?以上是关于设置特定日期和时间的通知[关闭]的主要内容,如果未能解决你的问题,请参考以下文章
无法快速将特定日期和时间添加到 UserNotifications