gpt4 book ai didi

android - 即使在应用程序关闭时也保持持续通知

转载 作者:行者123 更新时间:2023-11-30 01:05:01 24 4
gpt4 key购买 nike

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

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

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

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

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

有谁知道即使应用关闭也能保持通知的方法?

最佳答案

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

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>

关于android - 即使在应用程序关闭时也保持持续通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38941594/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com