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

Android Java实现多状态定时推送通知 请求代码示例

Android 定时发送通知实现方案(适配前台/后台/应用关闭状态)

针对你的需求,推荐使用WorkManager实现,它是Android Jetpack组件,专门用于处理需要在后台执行的任务,无论应用处于前台、后台甚至被关闭(只要未被强制停止),都能保证任务被调度。以下是完整代码示例:

1. 添加依赖

在模块级build.gradle.kts(或build.gradle)中添加WorkManager依赖:

dependencies {
    // WorkManager
    implementation("androidx.work:work-runtime-ktx:2.8.1")
}

2. 声明权限

在AndroidManifest.xml中添加必要权限:

<!-- Android 13+ 发送通知需要 -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<!-- 如果需要精确调度任务(可选) -->
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />

3. 创建通知渠道(Android 8.0+ 必需)

在自定义Application类或启动Activity中初始化通知渠道:

class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        createNotificationChannel()
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channelId = "periodic_notification_channel"
            val channelName = "定时通知"
            val channelDescription = "按设定间隔发送的通知"
            val importance = NotificationManager.IMPORTANCE_DEFAULT

            val channel = NotificationChannel(channelId, channelName, importance).apply {
                description = channelDescription
            }

            val notificationManager = getSystemService(NotificationManager::class.java)
            notificationManager.createNotificationChannel(channel)
        }
    }
}

别忘了在AndroidManifest.xml中注册MyApp:

<application
    android:name=".MyApp"
    ...>
    ...
</application>

4. 创建Worker类(处理通知发送逻辑)

创建一个继承自CoroutineWorker的类,在doWork方法中实现发送通知的逻辑:

class PeriodicNotificationWorker(
    context: Context,
    workerParams: WorkerParameters
) : CoroutineWorker(context, workerParams) {

    override suspend fun doWork(): Result {
        sendNotification()
        // 返回Result.success()表示任务执行成功,会按周期重复
        return Result.success()
    }

    private fun sendNotification() {
        val channelId = "periodic_notification_channel"
        val notificationIntent = packageManager.getLaunchIntentForPackage(packageName)?.apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        }
        val pendingIntent = PendingIntent.getActivity(
            applicationContext,
            0,
            notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )

        val notification = NotificationCompat.Builder(applicationContext, channelId)
            .setSmallIcon(R.drawable.ic_notification) // 替换成你的通知图标
            .setContentTitle("定时通知")
            .setContentText("这是按设定间隔发送的通知")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .build()

        val notificationManager = NotificationManagerCompat.from(applicationContext)
        // 检查通知权限(Android 13+)
        if (ContextCompat.checkSelfPermission(
                applicationContext,
                Manifest.permission.POST_NOTIFICATIONS
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            notificationManager.notify(1, notification)
        }
    }
}

5. 调度周期性任务

在启动Activity中触发任务调度,比如在onCreate方法中:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 请求通知权限(Android 13+)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            requestPermissions(
                arrayOf(Manifest.permission.POST_NOTIFICATIONS),
                1001
            )
        }

        // 调度周期性任务
        schedulePeriodicNotification()
    }

    private fun schedulePeriodicNotification() {
        // 设置任务间隔:这里是15分钟(WorkManager最小允许间隔)
        val periodicWorkRequest = PeriodicWorkRequestBuilder<PeriodicNotificationWorker>(
            15, TimeUnit.MINUTES
        ).build()

        // 将任务加入WorkManager队列,唯一任务ID避免重复调度
        WorkManager.getInstance(this).enqueueUniquePeriodicWork(
            "PeriodicNotification",
            ExistingPeriodicWorkPolicy.KEEP, // 如果已有相同ID任务,保留现有任务
            periodicWorkRequest
        )
    }
}

关键注意事项

  • 最小间隔限制:Android系统限制WorkManager周期性任务的最小间隔为15分钟,如果需要更短的间隔,系统后台限制会非常严格,不推荐实现(可能导致任务被系统杀死)。
  • 强制停止后的恢复:如果用户手动强制停止应用,WorkManager的任务会被取消,此时需要用户重新打开应用才能重新调度任务,无法自动恢复(这是Android系统的安全限制)。
  • 通知权限:Android 13及以上必须主动请求POST_NOTIFICATIONS权限,否则无法发送通知。
  • 图标要求:通知图标必须使用透明背景的图标,否则在部分设备上会显示为白色方块。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 02:30:47