java - Android:应用程序关闭时从后台推送动态通知

标签 java android android-intent notifications android-service

即使用户从 RAM 中删除了应用程序,我也需要从后台发送通知,从 Intent 中获取信息(放入通知中)作为额外内容。

目前,如果应用程序打开或在后台打开,它就可以工作,但当应用程序从最近的应用程序中关闭(从 RAM 中删除)时,它无法获取额外内容。

这是创建后台服务并将我需要传输的 ID 作为 Extra 的 Activity 。

AddEvent.java

// Gets the ID after it was generated by the database
        int ID = newEvent.getID();

        if (newEvent.hasNotification()) {
            // Creates the intent that starts the background service
            Intent serviceIntent = new Intent(this, NotificationService.class);

            // Puts the ID and the Notification Time as Extras and starts the service
            serviceIntent.putExtra(EXTRA_NOTIFICATION_ID,ID);
            serviceIntent.putExtra(EXTRA_NOTIFICATION_TIME,notificationDate.getTimeInMillis());
            startService(serviceIntent);
        }

此 Activity 启动我扩展的 IntentService。

NotificationService.java

public class NotificationService extends IntentService {

public NotificationService() {
    super("Notification Service");
}

@Override
protected void onHandleIntent(Intent workIntent) {

    // Create the intent that is going to push the notification, giving it the previous bundle
    Intent notificationIntent = new Intent(this, NotificationPusher.class);

    long notificationTime = workIntent.getLongExtra(ActivityAddEvent.EXTRA_NOTIFICATION_TIME,-1);
    int ID = workIntent.getIntExtra(ActivityAddEvent.EXTRA_NOTIFICATION_ID,-1);
    Log.d("ID Service",""+ID);
    notificationIntent.putExtra(ActivityAddEvent.EXTRA_NOTIFICATION_ID,ID);

    PendingIntent pusher = PendingIntent.getBroadcast(this, UniqueID.getUniqueID(),
            notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    //TODO : Can't get the Extras in Pusher
    
    // Sets the alarm for the designed date and time
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP,notificationTime,pusher);
}

public static class UniqueID {
    private final static AtomicInteger uniqueID = new AtomicInteger(0);
    public static int getUniqueID() {
        return uniqueID.incrementAndGet();
    }
}

}

它获取通知时间并将其设置到警报管理器,以便在所需的时间推送通知。

正确获取 ID 和时间(只要),然后将 ID 放入新 Intent 中,即发出通知的通知推送器。

NotificationPusher.java

public class NotificationPusher extends BroadcastReceiver {

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

    // Gets the event from the database using the ID received in the intent
    int ID = workIntent.getIntExtra(ActivityAddEvent.EXTRA_NOTIFICATION_ID, -1);
    Log.d("ID Pusher", "" + ID);


    EventManager eventManager = EventManager.getInstance(context);
    Event event = null;
    try {
        event = eventManager.getEvent(ID);
    } catch (SQLException e) {
        // TODO: Add error for id not found
        e.printStackTrace();
    }

    if (event != null) {
        String notificationTitle;
        String notificationText;
        // Sets the notification
        if (event.hasSubject()) {
            notificationTitle = event.getSubject() + "'s " + event.getType().toString();
            notificationText = context.getString(R.string.event_notification_default_text);
        } else {
            notificationTitle = event.getType().toString();
            notificationText = event.getTitle();
        }

        // Create the intent that is gonna be triggered when the notification is clicked and add to the stack
        Intent notificationIntent = new Intent(context, ActivitySingleEvent.class);
        notificationIntent.putExtra(ActivityAddEvent.EXTRA_NOTIFICATION_ID, ID);

        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
                Intent.FLAG_ACTIVITY_CLEAR_TASK);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, NotificationService.UniqueID.getUniqueID(),
                notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
       
        // Gets the default sound for notifications
        Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        // Create the notification with a title,icon,text,sound and vibration
        NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.ic_alarm_white_24dp)
                .setContentTitle(notificationTitle)
                .setContentText(notificationText)
                .setContentIntent(pendingIntent)
                // Notification auto cancel itself when clicked
                .setAutoCancel(true)
                .setSound(uri)
                .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
                .setLights(Color.BLUE, 3000, 3000);

        // Build the notification and issue it
        Notification notification = nBuilder.build();
        NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        nManager.notify(ID, notification);
    }
    else {
        Toast.makeText(context,"null event",Toast.LENGTH_SHORT);
    }
}

}

在通知推送器的顶部,它尝试从 Extras 获取 ID,但每次从 RAM 中删除应用程序时,它都会获取默认值 (-1)。 我不知道如何传递这个ID。

最佳答案

您需要使您的服务成为前台服务,这很可能需要永久的系统通知,但当应用程序本身关闭时它会保持 Activity 状态。

https://developer.android.com/guide/components/services.html#Foreground

关于java - Android:应用程序关闭时从后台推送动态通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37623203/

相关文章:

java - 安卓 : SMSManager - Attempt to get length of null array

java - 从 JAR 应用程序播放音频文件在 Linux 上不起作用

java - 如何在使用出站网关上传文件之前检查 aws s3 存储桶是否可用

android - 如何知道重新定义权限的数量?

java - 按钮点击不启动 Intent ?

java - Intent 未开始 Activity

android - 如何在 Android 中拍照、保存和获取照片

java - 我们可以传递方法参数的值和注释吗

android - 通过Gradle解决Bintray中的伪影(非jcenter)

Android Studio 3.0 - 设置未保存