即使应用关闭,也会继续发出通知

时间:2016-08-14 11:06:36

标签: android

我有一个应用程序经常将设备位置上传到服务器。

上传位置是在重复闹钟中完成的,即使用户退出应用并从最近的应用列表中清除它也能正常工作。

用户可以通过按应用按钮停止应用上传位置。

我需要向用户显示持续通知,指示应用程序处于活动状态并且当前正在上传该位置。我使用了持续通知(NotificationBuilder.setOngoing(true)),但是一旦用户退出应用并将其从最近的应用中移除,此通知就会消失。

我知道保留通知应该是可能的,因为有应用程序执行此操作。例如,uTorrent应用程序和WiFi ADB应用程序执行此操作。

有人知道即使应用程序关闭也能保留通知的方法吗?

1 个答案:

答案 0 :(得分:1)

启动粘性服务。用户(强制)在从最近列表中删除应用程序后关闭应用程序后立即重新启动该服务。该服务也在启动设备后直接启动,因此粘性通知永远不会消失。请记住,永远不会消失的粘性通知可能会让一些用户感到不安。

OngoingNotificationService.class:

public class OngoingNotificationService extends Service {

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

    }

    @Override
    public void onCreate() {
        // Check if notification should be shown and do so if needed

    }
}

OngoingNotificationServiceStarter.class:

public class OngoingNotificationServiceStarter extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent(context, OngoingNotificationService.class);
        context.startService(i);

    }
}

的AndroidManifest.xml:

<manifest>

   ...

   <application>

        ...

        <service android:name=".OngoingNotificationService" />

        <receiver android:name=".OngoingNotificationServiceStarterr">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

   </application>

</manifest>
相关问题