java - 应用程序关闭后仍保持 Activity 状态且不会锁定 UI 的服务

标签 java android multithreading service intentservice

在我的 Android 项目中,我需要启动一个 Service 来:

  1. 即使在应用程序关闭后仍保持 Activity 状态
  2. 不阻塞主线程

我分析了这个问题的服务、IntentServices 和线程:

使用服务并覆盖

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // Some nasty code
    return START_STICKY;
}

我实现了第一个目标,但是当我启动服务时我阻塞了主线程

使用IntentService并覆盖

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

@Override
protected void onHandleIntent(Intent intent) {
    // Same nasty code as before
}

我实现了第二个目标,因为我没有阻止 UI,但当我终止应用程序时服务就会终止。

然后我尝试使用 Service 启动一个Thread,如下所示:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            //The usual nasty code
        }
    });
    thread.start();
    return START_STICKY;
}

我得到了与第一种情况相同的结果(我阻止了 UI)。

我使用 myActivity.startService(myActivity, MyService.class) 启动服务

我是否遗漏了一些明显的东西?有没有办法同时实现这两个目标?

最佳答案

对于本例:

Stays alive even after the application closure.

你需要使用Service而不是IntentService,因为IntentService总是在onHandleIntent中的代码之后杀死自己被彻底处决。通过在ServiceonStartCommand方法中调用startForeground(int notification_id, Notification notification),将使您的Service仍然活着而不阻塞 UI 线程。但是您需要为 startForeground 方法创建一个通知。完成 Service< 后,不要忘记在 ServiceonDestroy() 方法中调用 stopForeground(true)/。请记住,如果您要执行的代码是异步的,请创建一个扩展 Handler 的私有(private)类 ServiceHandler,并在 handleMessage 方法中运行代码。

实现此模式的应用程序是 DU Battery Saver。

关于java - 应用程序关闭后仍保持 Activity 状态且不会锁定 UI 的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33895471/

相关文章:

java - 消费品生产商

C# TPL 每秒更新一次 Gridview

java - SSL - HTTPException : HTTP response '413: Request Entity Too Large' when communicating

java - 从 strings.xml 提供 layout_height 和 layout_width

java - 如何在我自己的项目中使用netbeans模块?

java - @WebServlet 中的拦截器未激活

android - 跨市场应用内计费

Android - 制作默认标签但没有任何内容

android - 尝试连接到数据库表时出现运行时错误

c# - 不同线程上的新表单