我有通知在用户点击按钮时工作。我希望在没有用户点击此按钮且不在应用程序上的情况下发送此通知。
实现这一目标的最佳方式是什么?
这是我从广播接收器获取祝酒词的按钮:
public void onetimeTimer(View view){
Context context = this.getApplicationContext();
if(alarm != null){
alarm.setOnetimeTimer(context);
}else{
Toast.makeText(context, "Alarm is null", Toast.LENGTH_SHORT).show();
}
这是我的闹钟管理器广播接收器:
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
final public static String ONE_TIME = "onetime";
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
//Acquire the lock
wl.acquire();
//You can do the processing here update the widget/remote views.
Bundle extras = intent.getExtras();
StringBuilder msgStr = new StringBuilder();
if(extras != null && extras.getBoolean(ONE_TIME, Boolean.FALSE)){
msgStr.append("One time Timer : ");
}
Format formatter = new SimpleDateFormat("hh:mm:ss a");
// msgStr.append(formatter.format(new Date()));
//msgStr.append();
Toast.makeText(context, msgStr, Toast.LENGTH_LONG).show();
//Release the lock
wl.release();
} 这是广播接收器中的方法:
public void setOnetimeTimer(Context context){
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
intent.putExtra(ONE_TIME, Boolean.TRUE);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pi);
}
这是一个按钮后面的通知,我希望警报管理器在没有按下按钮的情况下将其关闭。
Button btnNotifyWorkout = (Button)findViewById(R.id.btnNotifyWorkout);
btnNotifyWorkout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
PendingIntent pIntent = PendingIntent.getActivity(HomeActivity.this, 0, intent, 0);
Notification noti = new Notification.Builder(HomeActivity.this)
.setTicker("TickerTitle")
.setContentTitle("Lukes App")
.setContentText("You have a workout due today")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent).getNotification();
noti.flags = Notification.FLAG_AUTO_CANCEL;
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
nm.notify(0, noti);
}
});
答案 0 :(得分:0)
我可能无法正确理解您的问题,但我假设您想在触发警报时生成通知?
您可以将通知通知移动到BroadcastReceiver的onReceive。
你是否在清单中声明了接收者?