You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Toga/Beeware实现Android定时推送通知功能?

基于Toga/Beeware实现定时推送通知(Android为主)

已经有开发者实现过这类需求,核心思路是通过Beeware的原生平台桥接能力,调用Android系统的AlarmManager和NotificationManager API来实现定时通知,跨平台则需要针对不同系统做对应原生适配。以下是Android平台的具体实现步骤:

Android平台实现步骤

1. 添加Android原生辅助类

在你的Beeware项目的app/src/main/java/[你的包名]/目录下创建一个Java类(比如ScheduledNotificationHelper.java),负责处理定时任务和通知发送逻辑:

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;

public class ScheduledNotificationHelper extends BroadcastReceiver {
    private static final String CHANNEL_ID = "scheduled_notification_channel";
    private static final int NOTIFICATION_ID = 1001;

    // 调用此方法设置定时通知
    public static void scheduleNotification(Context context, long delayMillis, String title, String content) {
        // 创建通知渠道(Android 8.0+ 必需)
        createNotificationChannel(context);

        Intent intent = new Intent(context, ScheduledNotificationHelper.class);
        intent.putExtra("title", title);
        intent.putExtra("content", content);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(
            context,
            NOTIFICATION_ID,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
        );

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        long triggerTime = System.currentTimeMillis() + delayMillis;

        // 根据Android版本选择闹钟类型
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            if (alarmManager.canScheduleExactAlarms()) {
                alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
            }
        } else {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
        }
    }

    private static void createNotificationChannel(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "定时通知";
            String description = "用户设置的定时推送通知";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);

            NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String title = intent.getStringExtra("title");
        String content = intent.getStringExtra("content");

        Notification.Builder builder = new Notification.Builder(context, CHANNEL_ID)
            .setSmallIcon(android.R.drawable.ic_dialog_info)
            .setContentTitle(title)
            .setContentText(content)
            .setPriority(Notification.PRIORITY_DEFAULT);

        NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
        notificationManager.notify(NOTIFICATION_ID, builder.build());
    }
}

2. 在Python代码中调用原生方法

在你的Toga应用Python代码中,通过Beeware的android模块获取Android上下文,调用上述原生类的方法:

from toga import App, MainWindow, Button
import android

class ScheduledNotificationApp(App):
    def startup(self):
        self.main_window = MainWindow(title=self.formal_name)
        self.schedule_btn = Button("设置10秒后通知", on_press=self.schedule_notification)
        self.main_window.content = self.schedule_btn
        self.main_window.show()

    def schedule_notification(self, widget):
        # 获取Android Activity实例
        activity = android.activity.getActivity()
        # 调用原生辅助类的方法:延迟10秒发送通知
        activity.getClass().getClassLoader().loadClass("[你的包名].ScheduledNotificationHelper") \
            .getMethod("scheduleNotification", android.content.Context, long, str, str) \
            .invoke(None, activity, 10000, "定时通知", "这是你设置的定时推送内容")

def main():
    return ScheduledNotificationApp("定时通知Demo", "com.example.schedulednotification")

if __name__ == "__main__":
    main().main_loop()

3. 配置权限

在app/src/main/AndroidManifest.xml中添加必要权限:

<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />

<receiver android:name=".ScheduledNotificationHelper" />

跨平台适配思路

  • iOS平台:需要通过Beeware桥接调用UNUserNotificationCenter和UNCalendarNotificationTrigger/UNTimeIntervalNotificationTrigger实现定时通知,逻辑类似Android,需编写Objective-C/Swift辅助类。
  • 桌面平台(Windows/macOS/Linux):可使用Python的定时任务库(如schedule)结合Toga的通知API实现,但需注意应用在后台时的运行限制。

内容的提问来源于stack exchange,提问作者gimi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 18:32:11