App关闭时不触发AlarmManager

2024-01-04

我有一些应用程序内通知要在特定时间向用户显示,但应用程序关闭时不会显示任何内容。

设置闹钟:

Intent alarmIntent = new Intent(mMotherActivity, ReminderAlarmManager.class);

if (ReminderNotificationType.CHANGE_LENS.equals(notificationType)) {
    alarmIntent.putExtra("NOTIFICATION_TYPE", "REMINDER");
} else {
    alarmIntent.putExtra("NOTIFICATION_TYPE", "ORDER");
}

long scTime = alarmDate.getTime();
PendingIntent pendingIntent = PendingIntent.getBroadcast(mMotherActivity, 0, alarmIntent, 0);
AlarmManager alarmManager = (AlarmManager) mMotherActivity.getSystemService(mMotherActivity.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, scTime, pendingIntent);

广播接收器:

public class ReminderAlarmManager extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        String notificationType = intent.getStringExtra("NOTIFICATION_TYPE");
        if(notificationType.equalsIgnoreCase("ORDER"))
        {
            Intent i = new Intent(context, OrderReminderNotificationService.class);
            context.startService(i);
        }
        else if(notificationType.equalsIgnoreCase("REMINDER"))
        {
            Intent i = new Intent(context, ReminderNotificationService.class);
            context.startService(i);
        }
    }
}

所以当涉及到scTime时,即使应用程序关闭,我也想触发通知。所以我通过 PendingIntent 调用服务,如下所示:

public class OrderReminderNotificationService extends IntentService {

    public OrderReminderNotificationService(String name) {
        super(name);
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

        Context context = getApplicationContext();
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            context);

        Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        mBuilder.setContentTitle("Notification");
        mBuilder.setContentText(context.getString(R.string.renewOrderNotificationMsg));
        mBuilder.setSmallIcon(R.mipmap.ic_launcher);
        mBuilder.setSound(uri);
        mBuilder.setAutoCancel(true);

        Intent notificationIntent = new Intent(this, LoginActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(2, mBuilder.build());
}

清单中有关以下内容的部分:

<receiver android:name="com.company.utils.ReminderAlarmManager">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

但什么也没有出现...我做错了什么?


您的设备不允许您触发警报,因为它需要节省一些电池电量。 因此,转到“设置”->“电池/省电程序”->“应用程序”,然后选择您的应用程序,然后选择“无限制”

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

App关闭时不触发AlarmManager 的相关文章

随机推荐