0
我有一個報警管理器,它將當前時間放在一條消息中,並在Toast消息中輸出該消息。來自報警管理器的顯示通知
我想要做的是輸出通知,而不是吐司消息,並一直在努力這樣做。
Alarm Manager的工作原理。當按鈕按下按鈕(當前未連接到警報管理器)時,通知也可以正常工作。
這裏是我的按鈕是從廣播接收器獲取敬酒:
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);
}
這是通知是單獨工作在不同的背後t按鈕,我想通過按下報警管理器按鈕來啓動它。
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);
}
});
我加入w1.acquire和w1.release但它的通知不是通知NOTIFICATION_SERVICE,我收到錯誤:「NOTIFICATION_SERVICE無法解析爲變量」 – Coco12
對不起,我忘了調整它,只需用Context.NOTIFICATION_SERVICE替換即可。我已經調整了答案 –
這太棒了,它完美地解決了我的問題!謝謝您的幫助! :) – Coco12