gpt4 book ai didi

android - 检查通知是否处于 Activity 状态

转载 作者:行者123 更新时间:2023-11-29 14:48:58 25 4
gpt4 key购买 nike

我正在构建一个使用切换按钮启动的通知:

    toggleLigar.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(toggleLigar.isChecked()){
NotificationUtil.cancelaAll(TelaCriaDesp.this);

CharSequence tickerText = "Despertador ativado!";
CharSequence title = "Você não vai perder seu ponto!";
CharSequence message = "O despertador " + despertador.getNomeDesp() + " está ativo!";
Intent intent = new Intent(TelaCriaDesp.this, TelaCriaDesp.class);

NotificationUtil.criaNotification(TelaCriaDesp.this, tickerText, title, message,
despertador.getDesp_id(), intent);
} else {
NotificationUtil.cancelaNotification(TelaCriaDesp.this, despertador.getDesp_id());
}
}
});

现在我想根据通知状态将切换按钮分配为 ON 或 OFF,如果它处于 Activity 状态(正在显示)则为 ON,不活动为 OFF...我试过这个:

    public static boolean testaNotification(int id, Context context){
Intent intent = new Intent(context, TelaCriaDesp.class);
//intent.setAction(Intent.);
PendingIntent teste = PendingIntent.getActivity(context, id, intent,
PendingIntent.FLAG_NO_CREATE);
return teste != null;
}

但它不起作用,它总是返回 NULL...

这是我创建的通知:

   public class NotificationUtil {

@SuppressWarnings("deprecation")
public static void criaNotification(Context context, CharSequence tickerText, CharSequence title,
CharSequence message, int id, Intent intent){

PendingIntent aoSelecionar = PendingIntent.getActivity(context, 0, intent, 0);

Notification notification = null;
int apiLevel = Build.VERSION.SDK_INT;

if(apiLevel >= 11){
Builder montaNotification = new Notification.Builder(context)
.setContentTitle(tickerText)
.setContentText(message)
.setSmallIcon(R.drawable.icon)
.setContentIntent(aoSelecionar);

//montaNotification.setAutoCancel(true);
montaNotification.setOngoing(true);

if(apiLevel >= 17){
notification = montaNotification.build();
} else {
notification = montaNotification.getNotification();
}
} else {
notification = new Notification(R.drawable.icon, tickerText, System.currentTimeMillis());

notification.setLatestEventInfo(context, title, message, aoSelecionar);
//notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.flags |= Notification.FLAG_ONGOING_EVENT;
}

NotificationManager manager = (NotificationManager)
context.getSystemService(Activity.NOTIFICATION_SERVICE);

manager.notify(id, notification);

}

最佳答案

从 API 23 开始,您可以使用 NotificationManager 方法 getActiveNotifications()。这将以数组形式返回您的应用启动的 Activity 通知列表。

因此,要检查特定通知是否处于 Activity 状态,您只需遍历此数组的元素并比较通知 ID/标签即可。

在此处阅读有关此方法的更多信息: NotificationManager.getActiveNotifications()

关于android - 检查通知是否处于 Activity 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25252322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com