我有一个Notification.Builder
,只要我点击一个按钮就会向通知栏发送消息。有没有办法让通知在选定的时间出现?我查看了Android文档,但没有看到任何看起来可行的内容。
这是我的代码段:
Notification n = new Notification.Builder(this)
.setContentTitle("Random title")
.setContentText("Random text")
.setSmallIcon(R.drawable.abc_ic_go_search_api_mtrl_alpha)
.setContentIntent(pIntent).build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, n);
谢谢!
答案 0 :(得分:4)
1)使用您的通知代码创建广播接收器。
public class AlarmReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new NotificationCompat.Builder(context)
.setContentTitle("Random title")
.setContentText("Random text")
.setSmallIcon(R.drawable.abc_ic_go_search_api_mtrl_alpha)
.setContentIntent(PendingIntent.getActivity(context, 0, new Intent(context, MyActivity.class), 0))
.build();
notificationManager.notify(0, notification);
}
}
2)使用AlarmManager安排闹钟以广播您的广播接收器的意图。
AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
// set for 30 seconds later
alarmMgr.set(AlarmManager.RTC, Calendar.getInstance().getTimeInMillis() + 30000, alarmIntent);
答案 1 :(得分:1)
在您想要设置通知的地方使用此
//Create an offset from the current time in which the alarm will go off.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 15);
//Create a new PendingIntent and add it to the AlarmManager
Intent intent = new Intent(this, MyAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,
100, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
在此处显示您的通知
public class MyAlarmService extends Service
{
@Override
public IBinder onBind(Intent arg0)
{
return null;
}
@Override
public void onCreate()
{
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
// put notification code here
}
@Override
public void onDestroy()
{
super.onDestroy();
}
}