我有一个警报管理器,它将当前时间放入一条消息中,并在Toast消息中输出该消息。
我想要做的是输出通知而不是吐司消息,并且一直在努力这样做。
警报管理器有效。当按钮(当前未连接到警报管理器)按下时,通知也会正常工作。
这是我从广播接收器获取祝酒词的按钮:
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 :(得分:1)
尝试将通知代码放入" onReceive"在报警管理器接收器中
但是经过一些调整:
Intent intent = new Intent();
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0);
Notification noti = new Notification.Builder(context)
.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) context.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(0, noti);