android - IntentService 的 StartForeground

标签 android intentservice foreground-service

我有一个 IntentService,我想通过持续通知让它保持粘性。问题是通知出现然后立即消失。该服务继续运行。我应该如何在 IntentService 中使用 startForeground()

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    Notification notification = new Notification(R.drawable.marker, "Notification service is running",
            System.currentTimeMillis());
    Intent notificationIntent = new Intent(this, DashboardActivity.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|
        Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    notification.setLatestEventInfo(this, "App",
            "Notification service is running", pendingIntent);
    notification.flags|=Notification.FLAG_NO_CLEAR;
    startForeground(1337, notification);
    return START_STICKY;
}

@Override
protected void onHandleIntent(Intent intent) {

    String id = intent.getStringExtra(ID);
    WebSocketConnectConfig config = new WebSocketConnectConfig();
    try {
        config.setUrl(new URI("ws://" + App.NET_ADDRESS
                + "/App/socket?id="+id));
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    ws = SimpleSocketFactory.create(config, this);
    ws.open();
}

谢谢

最佳答案

这不应该是 IntentService。正如所写,您的 IntentService 将存在一毫秒左右。一旦 onHandleIntent() 返回,服务就会被销毁。这应该是一个常规的服务,您可以在其中创建自己的线程并管理线程和服务的生命周期。

Notification 立即消失的原因是服务立即消失。

关于android - IntentService 的 StartForeground,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9930729/

相关文章:

android - 如何在程序代码中启用 Android 上的位置?

android - java.lang.NullPointerException : lock == null while get json file from server 异常

android - GCMBaseIntentService 回调仅在根包中

java - 如何在固定时间间隔后使用 IntentService 实现进行轮询?

android - 如何正确停止前台服务?

java - GDAX API 错误请求 400

java - 有没有办法通过 LAN 以编程方式/命令行从 windows/linux 挂载 android 目录?

android - progressDialog 不在 onReceive 中关闭

java - 为什么设备进入休眠模式后前台服务停止工作

Android 8.1.0 前台服务通知问题