簡體   English   中英

即使應用程序被殺死也推送通知

[英]Push Notification even when app is killed

我有一個服務發送在onStartCommand()方法中安排的通知。 我希望它從后台發送通知,即使應用程序已關閉。 我設法做的是在應用程序打開以及應用程序在后台時發送通知。 但是,當我單擊 android 的概述按鈕並在應用程序上滑動以關閉它時,通知不再發送。

這是Service的代碼:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);

    Log.d("NotificationService", "onStartCommand");

    setupNotificationTimers();

    return START_STICKY;
}

setupNotificationTimers()在代碼下方運行,確保在所需日期運行postNotification()

Timer timer = new Timer();
long delay = notificationDate.getTime() - currentTime.getTime(); // how much time until notification should be sent

TimerTask timerTask = new TimerTask() {
    public void run() {
        handler.post(() -> postNotification(channel, "title", "content"));
    }
};

timer.schedule(timerTask, delay);

最后是我的postNotification方法:

private void postNotification(int channelIndex, String title, String content) {
    Log.d("NotificationService", "Posting notification...");
    Intent notificationIntent = new Intent(this, MainActivity.class);

    PendingIntent intent = PendingIntent.getActivity(this, 0,
            notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, notificationChannelId)
            .setSmallIcon(R.drawable.ic_note)
            .setContentTitle(title)
            .setContentText(content)
            .setAutoCancel(true)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setContentIntent(intent);

    notificationManager.notify(channelIndex, builder.build());
}

我發現的大多數解決方案都不適合我——例如return START_STICKY; onStartCommand()中。

此外,通過概覽按鈕關閉應用程序時,不會調用我的onDestroy()方法。 我不知道為什么,但這使我在服務被破壞時無法重新啟動服務

@Override
public void onDestroy() {
    Log.d("NotificationService", "Notification service destroyed"); // doesn't get logged
    stoptimers();
    super.onDestroy();
}

即使應用程序被殺死,我怎樣才能使服務運行?

編輯:

以下是AndroidManifest.xml中定義的服務和活動:

<service
    android:name=".NotificationService"
    android:label="@string/app_name">
    <intent-filter>
        <action android:name="your.app.domain.NotificationService" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</service>

<activity android:name=".MainActivity">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

Android 上沒有更多的后台服務。 通過在前台啟動通知來告訴設備保持您的服務運行。 只需更換

notificationManager.notify(channelIndex, builder.build());

startForeground(channelIndex, builder.build());

並保持onStartCommand返回START_STICKY

此外,通過概覽按鈕關閉應用程序時,不會調用我的 onDestroy() 方法。

根據官方 Android 文檔onDestroy() onStop() ) 是可殺死的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM