event的用法—通知

Event 是 python 锁机制的一种,用于通知线程是堵塞等待还是进行下一步操作。Event有一个标志_flag,在创建时默认初始化为False。set()方法设置Event状态标志_flag为True。clear()方法复位为False。
主要应用方法为wait(timeout)。timeout的单位为秒。wait的timeout参数为空,如标志_flag为False,则堵塞等待。否则执行下一步。在标志为False时,如果timeout参数不为空,则堵塞时间到后返回状态值,执行下一步。如标志为True,则直接执行下一步。
应用场景:简单的猜密码。用户输入一个字符串,如字符串不正确,则等待三秒后提示用户继续输入。直到用户输入正确字符串为止。
代码示例:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from time import ctime, sleep
from threading import Thread, Event
def inputchar():
    print('begin to input the correct chars\n')
    while True:
        if input() == 'abc':
            event.set()
            break


def showtip():
    while not event.wait(3):
        print('input chars:\n')
    print('you input correct chars')


if __name__ == '__main__':
    event = Event()
    event.set()
    event.clear()
    t1 = Thread(target=inputchar)
    t2 = Thread(target=showtip)
    t1.start()
    t2.start()

    t1.join()
    t2.join()

运行结果:

D:\Programs\Python\Python38-32\python.exe E:/PycharmProjects/cp/src/ch04/ex11_event.py
begin to input the correct chars

input chars:

input chars:

ainput chars:

aa
input chars:

aafaf
input chars:

abc
you input correct chars

Process finished with exit code 0
在 Android 中发送 `ONGOING_EVENT` 通知,可按以下步骤实现: 1. 创建 `NotificationCompat.Builder` 对象,用于构建通知。 2. 设置通知的基本属性,如小图标、标题和内容。 3. 设置点击通知后的响应,通常是启动一个 `Activity`。 4. 构建 `Notification` 对象,并设置其 `flags` 为 `Notification.FLAG_ONGOING_EVENT`,表示该通知为正在进行的事件。 5. 获取 `NotificationManager` 实例,用于发送通知。 6. 调用 `notify` 方法发送通知。 以下是示例代码: ```java NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("测试通知") .setContentText("Hello World"); // 设置点击通知之后的响应,启动 SettingActivity 类 Intent resultIntent = new Intent(this, SettingActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(pendingIntent); Notification notification = builder.build(); notification.flags = Notification.FLAG_ONGOING_EVENT; NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(1, notification); ``` 此代码通过 `NotificationCompat.Builder` 构建通知,设置了通知的基本属性和点击响应,将 `Notification` 的 `flags` 设置为 `Notification.FLAG_ONGOING_EVENT`,最后使用 `NotificationManager` 发送通知 [^1]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值