关于取消正在进行的通知,似乎还有其他问题 但是,我真的看了很多,但仍然没有解决方案。
SettingFragment
public class SettingFragment extends Fragment {
private Switch mSwitchNotific;
mSwitchNotific.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(isChecked){
Log.v(LOGTAG, "step notification on");
getContext().startService(new Intent(getContext(), UpdateStepNotificationService.class));
}else{
Log.v(LOGTAG, "step notification off");
NotificationManager notificationManager = (NotificationManager)
getContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(StickyUpdateStepNotification.NOTIFICATION_ID);
}
}
}
}
UpdateStepNotificationService
public class UpdateStepNotificationService extends Service {
static NotificationManager notificationManger;
StepsDBHandler stepsDBHandler;
public UpdateStepNotificationService() {}
@Override
public void onCreate() {
super.onCreate();
stepsDBHandler = new StepsDBHandler(getApplicationContext(), null, null, 0);
notificationManger = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
StickyUpdateStepNotification.NOTIFICATION_ID,
new Intent(getApplicationContext(), MainActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT);
final Notification notification = new Notification.Builder(
getApplicationContext())
.setSmallIcon(R.drawable.ic_notice)
.setContentTitle("Walksapp")
.setContentText("Now: " +Integer.toString(stepsDBHandler.getCurrentStepToday()) + " steps")
.setContentIntent(pendingIntent)
.build();
notification.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
new Timer().schedule(new TimerTask() {
@Override
public void run() {
notificationManger.notify(StickyUpdateStepNotification.NOTIFICATION_ID, notification);
}
}, 0, 1000);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
@Override
public void onDestroy() {
notificationManger.cancel(StickyUpdateStepNotification.NOTIFICATION_ID);
super.onDestroy();
}
}
UpdateStepNotificationService
重复发出包含最新步数的新通知
通知位于FLAG_NO_CLEAR
和FLAG_ONGOING_EVENT
打开和关闭通知的唯一方法是通过SettingFragment
中的切换按钮。
尝试:
notificationManger.cancel(StickyUpdateStepNotification.NOTIFICATION_ID);
不工作
希望看到任何输入 感谢
答案 0 :(得分:1)
您将需要终止计时器,否则它将继续更新通知。